I would have a rather simple question today. We have the following resource:
$a = array(1 => 5, 2 => 3, 3 => 13, 9 => array('test'), 4 => 32, 5 => 33);
How is it actually possible to find out if array "a" has an array element in it and return the key if there is one (or more)?
One possible approach:
function look_for_array(array $test_var) {
foreach ($test_var as $key => $el) {
if (is_array($el)) {
return $key;
}
}
return null;
}
It's rather trivial to convert this function into collecting all such keys:
function look_for_all_arrays(array $test_var) {
$keys = [];
foreach ($test_var as $key => $el) {
if (is_array($el)) {
$keys[] = $key;
}
}
return $keys;
}
Demo .
You can use foreach since you are looking for any array:
foreach ($a as $key => $test) {
if (is_array($test)) {
$keys[] = $key;
}
}
All keys of arrays for the array $a
will be in the array $keys
.
$array = array(1 => 5, 2 => 3, 3 => 13, 9 => array('test'), 4 => 32, 5 => 33);
foreach($array as $key => $value){
if(is_Array($value)){
echo $value[key($value)];
}
}
I have tried in different way.
$a = array(1 => 5, 2 => 3, 3 => 13, 9 => array('test'), 4 => 32, 5 => 33);
foreach ( $a as $aas ):
if(is_array($aas)){
foreach ($aas as $key => $value):
echo " (child array is this $key : $value)";
endforeach;
}else{
echo " Value of array a = $aas : ";
}
endforeach;
output is like :
Value of array a = 5 : Value of array a = 3 :
Value of array a = 13 : (child array is this 0 :
test) Value of array a = 32 : Value of array a = 33 :
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.