2
$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?

0

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That's not what I really needed, I mislead you, thank you nevertheless!
0

What I really need is removing an item from array of arrays in my Cache I tried this:

if(Cache::has('user_follower'.$user_id)){
        $user_follower = Cache::get('user_follower'.$user_id);

        foreach($user_follower as $key=>$follower){
            if($follower->user_id == Auth::id()){
                unset($user_follower[$key]);
                Cache::put('user_follower'.$user_id, $user_follower, 30);
                return;
            }
        }

}

I failed sadly, so I'm for now I'm using Cache::forget.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.