How to Add Elements to an Empty Array in PHP
Topic: PHP / MySQLPrev|Next
Answer: Use the array_push()
Function
You can simply use the array_push()
function to add new elements or values to an empty PHP array.
Let's take a look at an example to understand how it basically works:
Example
Try this code »<?php
// Adding values one by one
$array1 = array();
array_push($array1, 1);
array_push($array1, 2);
array_push($array1, 3);
print_r($array1);
echo "<br>";
// Adding all values at once
$array2 = array();
array_push($array2, 1, 2, 3);
print_r($array2);
echo "<br>";
// Adding values through loop
$array3 = array();
for($i=1; $i<=3; $i++){
$array3[] = $i;
}
print_r($array3);
?>
Related FAQ
Here are some more FAQ related to this topic: