0

I am trying to find an efficient way to do the following :

1) Parse an array. 2) If the element is a single value, store it/echo it. 3) If the element is an array, Parse it and store/echo all of its elements.

An example would be :

$array = array(15,25,'Dog',[11,'Cat','Cookie15'],22)

This would be echo'd as :

15 25 Dog 11 Cat Cookie15 22

Note : The maximum number of Nested layers of Arrays = 2 (The max is an Array within an Array, not deeper than that).

The code I have made so far is :

foreach($_POST as $key=>$value){  
      if(is_array($value))
      {
      <Not sure how to handle this condition! Need to parse the array and echo individual elements>
      }
      else
      {
       echo "Input name : $key Value : $value  ";
      }
}

Edit: The following is my dump for the array. The nested elements show blank for some odd reason!

string '15' (length=2)

string '25' (length=2)

string 'Dog' (length=3)

array (size=3)
  0 => string '' (length=0)
  1 => string '' (length=0)
  2 => string '' (length=0)

string '22' (length=2)

The relevant code is :

foreach($_POST as $input) {
 var_dump($input);
}
3
  • Where did that array come from? What created it? If it's a well-defined format, there surely must be existing code that will do it for you. Commented Sep 12, 2013 at 16:06
  • It is an array of answers from a Quiz! There are 3 types of answers, Single Choice (Radio Button), Multiple Choice (Checkbox) and Open Answer (User entered answer). While processing the array, it works well for Single and Open types, but for the checkbox (Which contains an array of the selected answers, and not just a single value), I ran into this problem! Commented Sep 12, 2013 at 16:44
  • So you're not actually parsing anything. You want to know how to handle nested arrays that you've been handed. Commented Sep 12, 2013 at 17:07

3 Answers 3

3

Using a RecursiveIteratorIterator and a RecursiveArrayIterator is definitely the cleanest way:

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));

foreach ($it as $key => $value) {
    var_dump($key, $value);
}


This was my old solution:

function handle($arr, $deepness=1) {
  if ($deepness == 3) {
    exit('Not allowed');
  }

  foreach ($arr as $key => $value) {
    if (is_array($value)) {
      handle($value, ++$deepness);
    }

    else {
      echo "Input name: $key Value: $value ";
    }
  }
}

handle($_POST);
Sign up to request clarification or add additional context in comments.

1 Comment

According to the first comment in the doco, recursive function is much faster than RecursiveIteratorIterator: php.net/manual/en/class.recursiveiteratoriterator.php
2

This should do the trick

PS.: I edit the call to the function, i was calling it inside a foreach, now i'm just sending $_POST wich is correct.

Second edit: I'm not saving the function inside a variable anymore, instead i'm declaring it.

function recursiveEcho($input){
    if (is_array($input)) {
        foreach ($input as $key => $value) {
            if (is_array($value)) {
                recursiveEcho($value);
            } else {
                echo "Input name: {$key} Value: {$value}";
            }
        }
    } else {
        // This is a string, there is no key to show
        echo "Input value: {$input}";
    }
};

recursiveEcho($_POST);

20 Comments

This fails when $input is a string!
I just tested it, @ComFreek is Right. If you wouldn't mind, can you please explain why it fails?
@SainathKrishnan Let's assume the first value of $_POST is a string and $recursiveEcho therfore gets passed a string. This won't do anything because $recursiveEcho only checks for arrays and does nothing otherwise.
Oh you meant it that way, I thought you meant it in the context of String/Integer/etc! Thanks for clearing that up! Got it! Then wouldn't that problem be fixed if the else statement of the inner loop was used in the outer loop as well?
@SainathKrishnan Correct, but this would be redundant (two echos with the same string and formats). Here is a cleaner solution: pastebin.com/8QRDCfM8
|
0

This will only handle 1 level. To handle x amount of levels, you either have to use a recursive function, or keep on nesting if statements.

foreach($_POST as $key => $value) {
   if(is_array($value) {
        foreach($value as $key2 => $value2) {
         echo "Key: " .  $key2 . "value: " .$value2;
        }
    } else {
        echo "key" .  $key . "value: ".  $value;
    }

}

1 Comment

For some reason $value2 is blank for all the elements of the nested array! $key2 has the correct values, though (The array index numbers)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.