1

I'm working with a two-dimensional array, and as I'm iterating through each index of this array, I'm trying to check if the current key is equal to a string.

Here's how I'm trying to do it:

foreach($_POST['items'] as $index => $item){

    $key = key($item);

    if($key == 'image'){
        echo 'hello';
    }

}

This throws the error Invalid argument supplied for foreach()

How do you check if the current key is equal to a particular string?

var_dump

array(2) { 
    [0]=> array(1) { ["paragraph"]=> string(4) "paragraph 1" } 
    [1]=> array(1) { ["paragraph"]=> string(4) "paragraph 2" } 
} 
array(2) { 
    [0]=> array(1) { ["paragraph"]=> string(4) "paragraph 3" } 
    [1]=> array(1) { ["paragraph"]=> string(4) "paragraph 4" } 
}

Here is the element within the form with name image:

<div><input type="file" name="items[][image]" id="uploadImage" multiple></div>

var_dump of dynamic form with 1 image input followed by 1 paragraph input

array(1) { 
    [0]=> array(1) { ["paragraph"]=> string(11) "paragraph 1" } 
} 

var_dump is not seeing the input with name image???

Here is the form Its contents are dynamically added from <script>

<form method="post" action="insert.php" enctype="multipart/form-data">

        <textarea name="title"></textarea>

        <input type="submit" name="upload" value="Upload" id="upload">
    </form>

One of the dynamic adding functions (this one is for image inputs)

    function addImage() {
    $("form").append('<div><input type="file" name="items[][image]" id="uploadImage" multiple></div>');
}
28
  • 1
    That error means $_POST['items'] is not something you can loop through with foreach. Your first step should be to make sure it's actually an array. Commented Jul 14, 2017 at 23:10
  • 1
    What is the contents of the $_POST['items'] variable? -- If you have not performed any processing on it then it is likely a String, and not an array. Commented Jul 14, 2017 at 23:11
  • 1
    I don't see how removing that if would have any bearing on the "Invalid argument supplied for foreach". Commented Jul 14, 2017 at 23:13
  • 1
    It doesn't change during the loop, so there's no need to do the same thing every time. But it doesn't matter. I tried to reproduce your error, I couldn't. Commented Jul 14, 2017 at 23:21
  • 1
    But if you're getting that error, you shouldn't get into the foreach loop at all. Are you sure the error is coming from this code? The error message should have a line number on it. Commented Jul 14, 2017 at 23:22

2 Answers 2

1

Check if $_POST['items'] is an array

if(is_array($_POST['items'])){
    foreach($_POST['items'] as $index => $item){

        $key = key($item);

        if($key == 'image'){
            echo 'hello';
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I didn't know about is_array. Without the if statement there are no errors.
Is the usage of is_array for testing purposes, or would you always use it when dealing with arrays?
@coffeebot You would use is_array() when you want to find out if a value is an array, context doesn't matter. For reference, see php.net/manual/en/function.is-array.php.
1

Another way is to use array_walk_recursive() which nicely takes care of the iteration for you; it is done implicitly and it's fast, too. So, if $_POST["items"] were similar to the following array, this example code shows how to test for an element whose key is "key":

<?php

$arr = ["1" => "a",
        "2" => "b",
        "3" => [10 => "apple",
                11 => "cat", 
                12 => ["key" => "image" ]]];

if ( array_walk_recursive($arr, function($item,$key) {

     if ($key == "key") {
           echo "\nKey is $key and item is $item";
      }


})) { echo "\narray_walk_recursive rocks :)";  }

See live code.

The built-in function array_walk() saves the coder from also having to check whether an element represents an array or a scalar value since the function possesses that kind of detection. The only thing that is required is to design the callback function, which in this case is an anonymous function.

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.