3

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

3
  • 3
    You can probably use in_array() Commented Feb 19, 2014 at 22:41
  • Is the array_diff() the function you are looking for? Commented Feb 19, 2014 at 22:41
  • 1
    I would probably loop through it and test with is_array - capture the key, and return the keys when you're done Commented Feb 19, 2014 at 22:42

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, I've tried the same, but this way, I will receive Warning: Invalid argument supplied for foreach() , because it's in the wrong format for the array one. I know I can just ignore it with @ but is there any other way around it?
Note that array typehint in the function's parameter. If you're not sure whether or not $test_var is an array, you should check it as well (with is_array) - but that probably means something else is wrong in your code.
Thank you I've found the issue in my code. The problem was that I've typed wrong some elements in the array actually. Thank you for the answer, I must by very tired that I've checked it multiple times and didn't see an error.
0
 $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)];
   }
 }

Comments

0

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 :

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.