Search code examples
phparray-push

Append several one-dimentional arrays to a one-dimentional array with array_push


I want to add data from a numeric, one-dimensional array to an existing one-dimensional total array, like in https://www.php.net/manual/de/function.array-push.php

My solution creates a two-dimentional array. Where is my logic error?

.
.
$arr_Total_WordText=array();

$i=0;
while ($row = $result->fetch_assoc()) {
    $text = utf8_encode(trim($row["mod_Thema"]));
    ...
    $arrWordText[$i]=$text;     // add several row-Infos
    $i++;
    array_push($arr_Total_WordText,$arrWordText);
}   

print_r($arr_Total_WordText);


[0] => Array
    (
        [0] => eins
        [2] => zwei
    )

[1] => Array
    (
        [0] => Drei
        [1] => vier
        [2] => fünf
    )

[2] => Array
    (
        [0] => sechs
        [1] => sieben
        [3] => acht
        [4] => neun
    )

Solution

  • array_push adds an element(s) to the end of the array. since you are pushing an array onto your result, it will add it as an array instead of concatenating, which is the reason it is creating a 2D array.

    You will need to use a technique that will concatenate/append the elements of the array to the result array.

    One way you can do this by using the array_merge function like so:

    $arr_Total_WordText = array_merge($arr_Total_WordText,$arrWordText);
    

    Another way is to iterate the elements of the array $arrWordText one by one and append them to your result.