Radical_Activity
Radical_Activity

Reputation: 2738

How to check if an array contains another array in PHP?

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)?

Upvotes: 3

Views: 13096

Answers (3)

Mubo
Mubo

Reputation: 1070

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 :

Upvotes: 0

raina77ow
raina77ow

Reputation: 106473

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.

Upvotes: 5

ZiupeX
ZiupeX

Reputation: 338

 $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)];
   }
 }

Upvotes: 0

Related Questions