0

I have a multidimensional array

(Array ( [filenames] => Array ( [0] => 2.jpeg [1] => 3.jpeg ) [sizes] => Array ( [0] => 0.00 MB [1] => 0.00 MB ) [temp_names] => Array ( [0] => /private/var/folders/np/sln14hvn3tsbzc4kpjjtp17c0000gn/T/phpLVhmBY [1] => /private/var/folders/np/sln14hvn3tsbzc4kpjjtp17c0000gn/T/phpoifsg0 ) [uploads] => Array ( [0] => /Users/sandro/Documents/bildgalerie/uploads/2.jpeg [1] => /Users/sandro/Documents/bildgalerie/uploads/3.jpeg ) ))

and I want to get all values from specific keys (like "filenames") with foreach.

Here is the part of the array:

$uploadData = array(
    'filenames' => array(),
    'sizes' => array(),
    'temp_names' => array(),
    'uploads' => array()
);

This code doesn't work yet, but I have no idea why :(

foreach ($uploadData as $row) {
    if (move_uploaded_file($row['temp_names'], $location . '/' . basename($row['filenames']))) {
        echo 'File uploaded.';
        echo '<br>';
    }
}

Error: Notice: Undefined index: filenames in X on line X

0

1 Answer 1

1

You're failing to understand what foreach is doing and how arrays are structured. It iterates over each element of the given array. You've said your data looks like this:

$uploadData = [
    'filenames' => ["2.jpeg", "3.jpeg"],
    'sizes' => ["0.00 MB", "0.00 MB"],
    'temp_names' => ["/private/var/folders/np/sln14hvn3tsbzc4kpjjtp17c0000gn/T/phpLVhmBY", "/private/var/folders/np/sln14hvn3tsbzc4kpjjtp17c0000gn/T/phpoifsg0"],
    'uploads' => ["/Users/sandro/Documents/bildgalerie/uploads/2.jpeg", "/Users/sandro/Documents/bildgalerie/uploads/3.jpeg"],
];

So, this is an array with 4 elements. Each iteration of the loop will give you a new element. First iteration you get an array ["2.jpeg", "3.jpeg"] and you're trying to access the filenames element of that array. Obviously there isn't one.

Instead you can just loop over one of the sub-arrays:

foreach ($uploadData["filenames"] as $key => $value) {
    if (move_uploaded_file($uploadData["temp_names"][$key], $location . '/' . basename($value))) {
        echo 'File uploaded.';
        echo '<br>';
    }
}

On the first iteration, $key will be 0 and $value will be 2.jpeg. You can use that key to get the matching values in the other sub-arrays.

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

1 Comment

That will do it :)

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.