1
$result = mysqli_query($con, "SELECT * FROM users");
$usersArray=[];
tableArrayPushData($result, $usersArray);

function tableArrayPushData($result, $tableArray){
    while ($row = $result->fetch_assoc()) {
        $str = '';
        foreach ($row as $value) {
            $str = $str.$value.'|';
        }
        $newStr = rtrim($str, "| ");
        array_push($tableArray,$newStr);
    }
}


for ($i=0; $i<count($usersArray); $i++){//array is always empty at this point
    echo "Ok";
    echo "<br>";
}

I don't understand why, but usersArray is empty despite the fact that I added data there.

The MySQL table has rows with data, so it can't be empty.

Ruben Kubalyan
  • 288
  • 3
  • 11
  • You should add some breakpoints in the loops to see e. g. how many time are the the loops called, you could add `print_r($row)` in the while loop to see what is in the array… – RatajS Aug 15 '21 at 16:48
  • 3
    Passing an array to a function without using the reference operator will only modify a value copy of the original array, not the actual array you pass to it. [SO post](https://stackoverflow.com/questions/2030906/are-arrays-in-php-copied-as-value-or-as-reference-to-new-variables-and-when-pas) provides quite some context and examples. – Remy Aug 15 '21 at 16:52
  • @Remy one moment. – Ruben Kubalyan Aug 15 '21 at 16:52

1 Answers1

1

You should use the & operator to allow the function to access the outer variable, like this:

function tableArrayPushData($result, &$tableArray) {}

Or use return.

RatajS
  • 1,403
  • 1
  • 14
  • 22