php - How to remove all items of array except specific one? -


i have variable containing these nested arrays:

echo $var;  /* output: array(        [0] => array          (              [id] => 1              [box] => 0          )         [2] => array          (              [id] => 2              [box] => 0          )         [3] => array          (              [id] => 3              [box] => 1          ) ) */ 

now want remove items of array above except $numb = 2; (the value of id). mean want output:

echo newvar;  /* output: array(        [2] => array          (              [id] => 2              [box] => 0          ) ) */ 

how can that?


actually can part of using if statement , array_shift() function:

foreach($var $key => $val) {     if($val["id"] != 2) {         array_shift($var);     } } 

but output of code above isn't want need.

you can use different loop.

foreach ($var $item) {     if ($item['id'] == 2) {         $newvar = $item;         break;     } } 

you use array_filter

$id = 2; $newvar = array_filter($var, function($x) use ($id) { return $x['id'] == $id; }); 

but less efficient have check every element of array.


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -