phparraysloopsmultidimensional-array

How to access data from a 2d array


I created an array that has values that are in groups of five, but I can't seem to figure out how to fetch them individually as I must in order to use them in calling another function.

Sample array contains:

Array
(
    [0] => Array
        (
            [0] => Your Full Name
            [1] => Name
            [2] => 1
            [3] => 
            [4] => 50
        )

    [1] => Array
        (
            [0] => Your Email
            [1] => EMail
            [2] => 1
            [3] => 
            [4] => 50
        )

    [2] => Array
        (
            [0] => Message
            [1] => Message
            [2] => 5
            [3] => 5
            [4] => 50
        )
)

The PHP snippet for using it:

$Values = array_chunk($Values, 5);
foreach ($Values as $row) :
    foreach ($row as $key) :
        valueTypes($key[0], $key[1], $key[2], $key[3], $key[4], "db_name");   
    endforeach;
endforeach;

Solution

  • You're doing it wrong. You need only one foreach.

    Snippet

        $Values = array_chunk($Values, 5);
        foreach ($Values as $key) :
           valueTypes($key[0], $key[1], $key[2], $key[3], $key[4], "db_name");
        endforeach;
    

    Explanation:

    Your array is multidimensional array, if you use two nested foreach , $key becomes string, and $key[0](Key Index) have no data.