Syntax:
array_push(array_input,value,………..)
Parameters:
- array_input is the array.
- Value/s will be added to the array at the end.
Let’s see examples to understand this concept better.
Example 1:
In this example, we will create an array with 4 values: ‘lotus’,’lilly’,’jasmine’,’rose’.
Now, we will add the value ‘marigold’ to the array.
//create an array named Flower1 with 4 values.
$Flower=array('lotus','lilly','jasmine','rose');
echo "Actual Array: ";
print_r($Flower);
//append 'marigold' to the Flower array.
array_push($Flower,'marigold');
echo "Final Array: ";
print_r($Flower);
?>
Output:
We can see that marigold has been added to the Flower array.
Example 2:
In this example, we will create an array with four values: ‘lotus’,’lilly’,’jasmine’,’rose’.
Now, we will add three values-‘marigold’,’rose’,’lotus’ to the array.
//create an array named Flower1 with 4 values.
$Flower=array('lotus','lilly','jasmine','rose');
echo "Actual Array: ";
print_r($Flower);
//append ‘marigold’,’rose’,’lotus’ to Flower array.
array_push($Flower,'marigold','rose','lotus');
echo "Final Array: ";
print_r($Flower);
?>
Output:
We can see that ‘marigold’,’rose’,’lotus’ have been added to the Flower array. If you want to add values to the key-value pair array, then the values will also get the keys with numeric values.
Example 3:
In this example, we will create an array with four key-values: ‘flower1’=>’lotus’,’flower2’=>’lilly’,’flower3’=>’jasmine’,’flower4’=>’rose’.
Now, we will add 3values-‘marigold’,’rose’,’lotus’ to the array.
//create an array named Flower1 with 4 key-values.
$Flower=array('flower1'=>'lotus','flower2'=>'lilly','flower3'=>'jasmine','flower4'=>'rose');
echo "Actual Array: ";
print_r($Flower);
//append ‘marigold’,’rose’,’lotus’ to the Flower array.
array_push($Flower,'marigold','rose','lotus');
echo "Final Array: ";
print_r($Flower);
?>
Output:
We can see that ‘marigold’,’rose’,’lotus’ have been added to the Flower array with keys-0,1 and 2.
Example 4:
In this example, we will create an array with four key-values: 1=>’lotus’,2=>’lilly’,3=>’jasmine’,4=>’rose’.
Now we will add 3 values-‘marigold’,’rose’,’lotus’ to the array.
//create an array named Flower1 with 4 key-values.
$Flower=array(1=>'lotus',2=>'lilly',3=>'jasmine',4=>'rose');
echo "Actual Array: ";
print_r($Flower);
//append ‘marigold’,’rose’,’lotus’ to Flower array.
array_push($Flower,'marigold','rose','lotus');
echo "Final Array: ";
print_r($Flower);
?>
Output:
We can see that ‘marigold’,’rose’,’lotus’ have been added to the Flower array with keys-5,6 and 7.
Conclusion
In this article, we saw how to append elements to the PHP array using the array_push() function.
It is possible to add single or multiple elements to the array at a time. We have to notice that if we add values to the key value pair array, then the newly added elements will be assigned keys of numeric type.