1

I have a big array of identical sub-arrays, a minimal example may look like:

array(4) {
  [0]=>
  array(2) {
    ["id_product"]=>
    string(4) "1372"
    ["quantity"]=>
    int(0)
   }
  [1]=>
  array(2) {
    ["id_product"]=>
    string(4) "1373"
    ["quantity"]=>
    int(1)
   }
  [2]=>
  array(2) {
    ["id_product"]=>
    string(4) "1374"
    ["quantity"]=>
    int(2)
   }
  [3]=>
  array(2) {
    ["id_product"]=>
    string(4) "1375"
    ["quantity"]=>
    int(0)
   }
}

My goal is to create a new array excluding the sub-arrays with quantity equal to int(0), what might give something like:

array(4) {
  [1]=>
  array(2) {
    ["id_product"]=>
    string(4) "1373"
    ["quantity"]=>
    int(1)
   }
  [2]=>
  array(2) {
    ["id_product"]=>
    string(4) "1374"
    ["quantity"]=>
    int(2)
   }
}

I tried using array_search() and unset() but to no avail. Any suggestions on how to use these functions so that I can exclude any subarray with condition like : sub-key= x and value = y.

Thank you very much for helping me.

2 Answers 2

1

A prefect situation to use array_filter()

$newArray = array_filter(
    $originalArray,
    function($value) {
        return $value['quantity'] > 0;
    }
);
Sign up to request clarification or add additional context in comments.

3 Comments

The question required filtering out elements in an array, based on a condition, and creating a newly filtered array. A perfect case for using array_filter()
This worked perfectly for me, It addressed the problem like a charm. I think some upvotes should be put here instead of downvoting because the use of unset and array_search was a waste of time(for me).
Perhaps I was downvoted for my spelling of perfect
1

Try your custom code

function array_filter(){
    $newArray = array();
    foreach($array as $key => $value){
        if($value["quantity"] > 0)
            $newArray[] = $value
    }
    return $newArray;
}

Enjoy :)

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.