Q:

How to Add Elements to an Empty Array in PHP

0

How to Add Elements to an Empty Array in PHP

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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:

<?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);
?>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now