Add data dynamically to an Array
To add data dynamically to an array in PHP, you can use the $array[] = $value
syntax. For example:
<?php
$array = [];
// Add a new element to the array
$array[] = 'apple';
// Add another element to the array
$array[] = 'banana';
// Add a third element to the array
$array[] = 'orange';
print_r($array);
This will add the elements 'apple', 'banana', and 'orange' to the array $array
.
You can also use the array_push()
function to add elements to the end of an array:
<?php
$array = [];
// Add a new element to the array
array_push($array, 'apple');
// Add another element to the array
array_push($array, 'banana');
// Add a third element to the array
array_push($array, 'orange');
print_r($array);
This will have the same effect as the previous example.
If you want to add an element to the beginning of an array, you can use the array_unshift()
function:
<?php
$array = [];
// Add a new element to the beginning of the array
array_unshift($array, 'apple');
// Add another element to the beginning of the array
array_unshift($array, 'banana');
// Add a third element to the beginning of the array
array_unshift($array, 'orange');
print_r($array);
This will add the elements 'orange', 'banana', and 'apple' to the array $array
, in that order.