1

I have an array like this:

Array ( [0] => Array ( [pid] => 8 [bv] => 0 [bs] => 0 ) [1] => Array ( [pid] => 11 [bv] => 0 [bs] => 0 ) [2] => Array ( [pid] => 10 [bv] => 0 [bs] => 0 ) ) 

as you see this array includes other arrays. Now I want to delete array with [pid] = 8 , for deleting that I need that array key but I don't know how to find the key of array that have pid=8 .

I tried this code but it doesn't work:

$key = array_search($pid, $cart_e); // $cart_e is above array

For Example:

For deleting array with pid = 8 I want the result be like this after deleting:

Array ( [1] => Array ( [pid] => 11 [bv] => 0 [bs] => 0 ) [2] => Array ( [pid] => 10 [bv] => 0 [bs] => 0 ) )

as you see the whole array is deleted (I need this code), in some case I just deleted pid that result become like this(I don't want this):

Array ( [0] => Array ( [bv] => 0 [bs] => 0 ) [1] => Array ( [pid] => 11 [bv] => 0 [bs] => 0 ) [2] => Array ( [pid] => 10 [bv] => 0 [bs] => 0 ) )

so, How to find the array key of a pid with specific id?

3
  • $res = array_filter(function ($x) { return $x['pid'] != 8;}, $array); Commented Sep 12, 2018 at 6:28
  • what is $x? should I replace it with something or just leave it? Commented Sep 12, 2018 at 6:32
  • @MSHDeveloper array_filter will iterate each item of your array and $x is the current element it is into and checking Commented Sep 12, 2018 at 6:38

1 Answer 1

2

How about creating a new copy of array using array_filter?

$array=array(array('pid'=>8,'bv'=>0,'bs'=>0),array('pid'=>11,'bv'=>0,'bs'=>0),array('pid'=>10,'bv'=>0,'bs'=>0));
$newArr = array_filter($array,function($arr){ /* `$arr` gets value of one nested array on each pass */
    return 8 !== $arr['pid'];
});

Or, just unset the unwanted nested array:

foreach($array as $key => $val){
    if(8 === $val['pid']){
        unset($array[$key]);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Dude, please give me a hand for how to use this code. I have two arrays (one parent others are inside). what is $array and $arr?
Well, it works like a charm, I used your second code for deleting that array. thanks.

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.