0

I have an array of objects ($response) that looks like this:

Array
(
    [0] => stdClass Object
        (
            [CardNumber] => 5897853070424xxx
            [CardHolderName] => P Stoltz
            [CardHolderContactNumber] => 
            [CardHolderEmailAddress] => 
            [CardExpiryDate] => 2017-09-01T00:00:00
            [CardHolderTypeID] => 2
            [LastUsedDate] => 2017-05-25T00:00:00
        )
    [1] => stdClass Object
        (
            [CardNumber] => 589785304326xxx
            [CardHolderName] => J Stoltz
            [CardHolderContactNumber] => 
            [CardHolderEmailAddress] => 
            [CardExpiryDate] => 2017-09-01T00:00:00
            [CardHolderTypeID] => 2
            [LastUsedDate] => 2017-05-25T00:00:00
        )

)

Now, I need to unset the entire object where CardNumber != '589785304326xxx'

I have tried this:

$cardnumber = '5897853070424xxx'; 
    foreach( $response as $res )
    {
        if($res->CardNumber != $cardnumber)
        {
            unset($res);
        }
    }

This does nothing. Any suggestions?

1
  • I would rather suggest an array_filter. Commented Jun 21, 2017 at 11:08

2 Answers 2

2

What you have tried will only unset the current object in the loop. You need to do the following:

foreach($response as $key => $res) {
    if($res->CardNumber != $cardnumber) {
        unset($response[$key], $res);
        continue;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

That continue is rather superfluous there.
Thank you @Ryan Hipkiss - that works brilliantly. Will accept as soon as the timer allows me.
@deceze put it in just to be sure xD
-1

Use unset() inside the loop.

eg:

unset('key value', 'your array name');

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.