Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Object from array by object value in php

Tags:

php

laravel

$followers = [['id'=>0], ['id'=>1]];

So, assuming I have this array, what would be the best way to remove the object by it's id?

That's what i came up with

foreach($followers as $key=>$follower){
    if($follower->id == 0){unset $followers[$key]}
}

is there a better more efficient way?

like image 270
Guy Mazouz Avatar asked Nov 28 '25 14:11

Guy Mazouz


1 Answers

It is an array not an object, so why are you accessing as an object?

Try this,

foreach ($followers as $key => $follower) {
    if($followers[$key] == 0) {
        unset($followers[$key]);
    }
}
  1. You were accessing values of an array like an object.

  2. You were using unset incorrectly.

  3. You were missing the ; at the end of your unset part.

like image 123
Script47 Avatar answered Nov 30 '25 03:11

Script47



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!