1

Let's say I have an array like this one:

$cart = [
  [ 'productID' => '11111' , 'size' => 'M' , 'quantity' => 2 ],
  [ 'productID' => '11111' , 'size' => 'L' , 'quantity' => 4 ],
  [ 'productID' => '22222' , 'size' => 'S' , 'quantity' => 3 ],
  [ 'productID' => '22222' , 'size' => 'L' , 'quantity' => 7 ],
  [ 'productID' => '33333' , 'size' => 'M' , 'quantity' => 1 ]
];

Now I would like to be able to delete from array by multiple values like this:

removeElementFromArray( $cart , [ 'productID' => '11111' , 'size' => 'M' ] );

But my problem is I do not understand the logic how to achieve this. This is what I have

function removeElementFromArray($targetArray=[],$needles=[]){

  foreach( $targetArray as $subKey => $subArray ){

    // This is wrong because $removeIt becomes TRUE by any needle matched
    // but I want it to become TRUE only if all $needles match.
    foreach( $needles as $key => $value ){
      if( $subArray[$key] == $value ){
        $removeIt = TRUE;
      }
    }

    // delete row from array
    if( $removeIt == TRUE ){ unset($targetArray[$subKey]); }

  }

  // return
  return $targetArray;

}

2 Answers 2

1

A simple modification to your code can work. This starts off assuming that you can remove an element, then if any of the values don't match, then flag it as not matching (and stop looking)...

function removeElementFromArray($targetArray=[],$needles=[]){

    foreach( $targetArray as $subKey => $subArray ){
        $removeIt = true;
        foreach( $needles as $key => $value ){
            if( $subArray[$key] !== $value ){
                $removeIt = false;
                break;
            }
        }

        // delete row from array
        if( $removeIt == TRUE ){ 
            unset($targetArray[$subKey]); 
        }

    }

    // return
    return $targetArray;

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

Comments

1

Ultra short array_filter version with array_diff_assoc:

function removeElementFromArray($targetArray, $needles) {
    return array_filter($targetArray, function ($item) use ($needles) {
        return !empty(array_diff_assoc($needles, $item));
    });
}

Fiddle here.

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.