Creating an empty 2D array in PHP?

Viewed 70099

I know that arrays are created dynamically, and creating them ahead of time isn't really necessary, but how would one do that with a 2D array? The same way?

(for$j)
{
for($i)
    {
    $array[j][i] = "data";
    }
}

Something like that? Obviously real for loops, of course.

8 Answers

Remember that whenever you use array(array()) nested function or the short array syntax [[]] both will create a 2D array with an empty element in the first position. This may bring you some errors so we needs to be removed it.

How we can remove an empty element?

Well it is absolute simple as calling the array_pop() method to pop the element[0] off the array, as this:

<?php
    $a = array(array());
    echo 'Before removing the empty element: \n'
    print_r($a);
    array_pop($a);
    print_r($a);

    $b = [[]];
    echo 'Before removing the empty element: \n'
    print_r($b);
    array_pop($b);
    print_r($b);
?>
Related