0

In PHP, the following statement both defines an array and inserts an element into the array:

$arr[] = $element

An example of the use of this statement (in a loop) is shown below. (It is from this PHP MySQli tutorial):

while ($row = $result->fetch_assoc())
{
  $ids[] = $row['id'];
  $names[] = $row['name'];
  $ages[] = $row['age'];
}
  1. Where is this syntax documented in the official PHP documentation?

  2. Please explain this syntax.

SSteven
  • 733
  • 5
  • 17
  • 1
    https://www.php.net/manual/en/language.types.array.php – Mat Jul 23 '21 at 08:25
  • Does this help? https://stackoverflow.com/questions/5964420/does-php-have-autovivification – Dharman Jul 23 '21 at 11:33
  • The official PHP page on Arrays (for which Mat provided a link) calls this feature "Array append". – SSteven Jul 23 '21 at 11:55
  • You need to be more clear what information you are looking for. Of course it is called array append, because you append (push) values to the array. The syntax you are describing is called array autovivification. It creates an array even if one wasn't defined earlier. – Dharman Jul 23 '21 at 12:10

2 Answers2

0

There is nothing special with array_push in loop (You are using while loop) and initilizing values to an array ($arr[] = $element). The only differene is you are pushing value into the array through while loop and declaring initially using assignment operator.

In your case, you have initilized $element to the array

$arr[] = "123"; //Lets say 123 is $element
$arr[] = "NAME"; //Same way, you can repeat in next line as well
$arr[] = "45";

echo '<pre>';
print_r($arr);

// And the output was 
Array (
    [0] => 123
    [1] => NAME
    [2] => 45
)

And the next statement was

while ($row = $result->fetch_assoc())
{
  $ids[] = $row['id'];// Lets say 123 is $row['id'];
  $names[] = $row['name']; //Lets say NAME is $row['name'];
  $ages[] = $row['age']; //Lets say 45 is $row['age'];
}

//The output will be same if only one row exist in the loop
Array (
 [0] => 123
 [1] => NAME
 [2] => 45
 .................. // Based on while loop rows
)

The symbol [] will push value into array because you didn't mention any key in between bracket.

Rinshan Kolayil
  • 1,111
  • 1
  • 9
  • 14
-1
$ids[] = $row['id'];  

Here we group the returned id element (from the SQL query) into one array. Thus finally, the ids array will store all the id elements from the SQL query; likewise for the other arrays.

The syntax $id [] = $value means we are pushing the $value element into the array.

Dharman
  • 30,962
  • 25
  • 85
  • 135