Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

509
Views
Why using unset() function cast the array to object?

Here is my code:

return ApiResponse::Json(200, '', ['categories' => $categories], 200);

And here is a screenshot of the result:

output 1

Now, I need to unset items inside categories collection based on a specific logic. So I wrote this loop:

foreach ($categories as $key => $category) {
    if ($category->BusinessSubCategory->isEmpty())
          unset($categories[0]);
}

return ApiResponse::Json(200, '', ['categories' => $categories], 200);

And here is my new result: (which is casted to an object)

output 2

Well .. What's wrong? How can I keep the old structure after unseting some items?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Try this:

foreach ($categories as $key => $category) {
    if ($category->BusinessSubCategory->isEmpty())
          unset($categories[$key]);

}

$categories = array_slice($categories->toArray(), 0, count($categories));

return ApiResponse::Json(200, '', ['categories' => $categories], 200);
over 4 years ago · Santiago Trujillo Report

0

The unset() method doesn't change your type.

Your 'array' is not an array but a collection.

Try:

foreach ($categories as $key => $category) {
    if ($category->BusinessSubCategory->isEmpty()) {
        unset($categories[0]);
        break;
    }
}
$categories = array_values($categories->toArray());

return ApiResponse::Json(200, '', ['categories' => $categories], 200);

Notice if you're unseting the same element you should break loop after do that.

over 4 years ago · Santiago Trujillo Report

0

Look like you are using relationship so you can do without loop

$category=Category::with('BusinessSubCategory')
                     ->has('BusinessSubCategory')
                     ->get();

or using collection

$result= $categories->filter(function ($category){
    
           return  $category->BusinessSubCategory->isNotEmpty();
        });

dd($result->values()->toArray());

if $categories is not collection then use collect($categories)->filter...

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!