September 2, 2013
how to delete an array which contains a specified string
Zaz’s Question:
I have an array called “VALUES” that contains multiple arrays. In these array there is a field named “test”, I only want the arrays pointed out that contains the number 4 in the test field.
my current output for Values array:
Array (
[0] => Array ( [entry_id] => 41149 [o_number] => 000001 [test1] => 000001 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 )
[1] => Array ( [entry_id] => 41142 [o_number] => 000202[test1] => 000202 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 )
[2] => Array ( [entry_id] => 41103 [o_number] => 000003 [test1] => 000003 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 )
[3] => Array ( [entry_id] => 41101 [o_number] => 000044 [test1] => 000044 [test2] => 1234 [lev] => Ja [fak] => Manuel/brev [beta] => 10 [test] => 2 )
[4] => Array ( [entry_id] => 41100 [o_number] => 000542 [test1] => 000542 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 )
[5] => Array ( [entry_id] => 41088 [o_number] => 001231 [test1] => 001231 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 3 ))
desired output:
Array (
[0] => Array ( [entry_id] => 41149 [o_number] => 000001 [test1] => 000001 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 )
[1] => Array ( [entry_id] => 41142 [o_number] => 000202[test1] => 000202 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 )
[2] => Array ( [entry_id] => 41103 [o_number] => 000003 [test1] => 000003 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 )
[3] => Array ( [entry_id] => 41100 [o_number] => 000542 [test1] => 000542 [test2] => 1234 [lev] => Ja [fak] => Mail [beta] => 30 [test] => 4 ))
I tried with a foreach but it didn’t work
foreach ($values as $key)
{
if($key === 4)
{
//This will only show
print_r($key);
//delete array?
}
}
Try following codes:
foreach ($values as $key => &$value)
{
if($value['test'] != "4")
unset($values[$key]);
}
var_dump($values);
Since you are using multidimensional arrays it is not that easy to check whether or not any array consists of that key, without traversing through it. In order to traverse, you can use foreach
foreach($values as $array) {
//Now here you can check if the there is `test` index available or is of value `4`
if(isset($array['test'])) && $array['test'] == '4') {
//Only then output it
var_dump($array);
}
}
It is that simple.