Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

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

like image 817
Radical_Activity Avatar asked Mar 04 '26 03:03

Radical_Activity


1 Answers

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.

like image 56
raina77ow Avatar answered Mar 05 '26 17:03

raina77ow