For this nested array:
$status = array( "house" => "OK", "car" => array( "car1" => "OK", "car2" => "ERROR" ), "boat" => "OK" );
I want to know if a certain value “ERROR” exists at least once in the array. I don’t care what key it’s associated with, I just want to know if the $status array contains an “ERROR” status anywhere in it.
Is there a cleaner way to do this than just iterating over the elements with nested for loops?
Advertisement
Answer
You could use the function array_walk_recursive()
to get all the values with any level of nested array.
https://secure.php.net/manual/en/function.array-walk-recursive.php
<?php $status = array( "house" => "OK", "car" => array( "car1" => "OK", "car2" => "OK" ), "boat" => "OK" ); $required = array(); array_walk_recursive($status, function ($value, $key) use (&$required){ $required[] = $value; }, $required); print '<pre>'; print_r($required); print '</pre>'; ?>
Output:
Array ( [0] => OK [1] => OK [2] => OK [3] => OK )