I have a simple array of boolean arrays as follows:
array(
array('dog' => true),
array('cat' => true),
array('bird' =>false),
array('fish' => true)
)
How can I find an entry, such as 'cat', without a loop construct? I think I should be able to accomplish this with a php array function, but the solution is eluding me! I just want to know if 'cat' is a valid key - I'm not interested in it's value.
In the example above, 'cat' should return true, while 'turtle' should return false.
$array = array(
array('dog' => true),
array('cat' => true),
array('bird' =>false),
array('fish' => true)
);
array_walk($array,'test_array');
function test_array($item2, $key){
$isarray = is_array($item2) ? 'Is Array<br>' : 'No array<br>';
echo $isarray;
}
using array_walk example in the manual
Output:
Is Array
Is Array
Is Array
Is Array
This is a ridiculous way of storing keys. There is no point making each key an array by itself if it's going to have just one element.
A much more sensible way of doing what I think you want to do is:
$myArray = array(
'dog' => true,
'cat' => true,
'bird' => false,
'fish' => true)
)
In which case you could check if a key exists using array_key_exists
.
If you have to use the current array structure, then looping is the only way to check.
You could achieve it like this :
Your array :
$yourArray = array
(
array( 'dog' => true )
,array( 'cat' => true )
,array( 'bird' =>false )
,array( 'fish' => true )
);
Code to check if a key exists :
$itemToFind = 'cat'; // turtle
$result =
array_key_exists
(
$itemToFind
,array_reduce(
$yourArray
,function ( $v , $w ){ return array_merge( $v ,$w ); }
,array()
)
);
var_dump( $result );
Code to check if a key exits and to retrieve its value :
$itemToFind = 'cat'; // bird
$result =
array_key_exists
(
$itemToFind
,$reducedArray = array_reduce(
$yourArray
,function ( $v , $w ){ return array_merge( $v ,$w ); }
,array()
)
) ?$reducedArray[ $itemToFind ] :null;
var_dump( $result );
Using PHP > 5.5.0
You could use combination of array_column and count PHP functions to achieve it :
Code to check if a key exists :
$itemToFind = 'cat'; // turtle
$result = ( count ( array_column( $yourArray ,'cat' ) ) > 0 ) ? true : false;
var_dump( $result );
The above code tested with PHP 5.5.5 is here