PHP array_​push Function



array_​push () is a prebuilt / default array function of PHP, This function is basically allows user to add one or more elements at the end of any existing array. By using this function user can add any number of the element at the end, and this element can be string and numeric as well. The length of array increases by the elements (numbers/string) pushed.

Syntax of array_push :

array_push(array &$array, mixed ...$values)

array_push () has one or more parameters in which one parameter is required and the other one is optional parameters. These parameters are as follows with a brief description –

array (required) – It is an array parameter. It is required to pass in this function. This array can contain any type of value, like string or numeric.

values – (required before 7.3 and optional with latest version of PHP) – This parameter contains the value to be pushed into the array.

Return Value :
The array_push() returns number of elements in array with all the elements present in the array after they have pushed in it.

Example 1 :

<?php
    $vehicle = array("hyundai", "suzuki");
	$vehicle_no = array_push($vehicle, "mghector", "tata", "nissan");
	print_r($vehicle_no); 
?>

Output will be : 5

Example 2 :

<?php
	$vehicle = array("hyundai", "suzuki");
	array_push($vehicle, "mghector", "tata", "nissan");
	print_r($vehicle);
?>

Output will be:

Array 
( 
	[0] => hyundai 
	[1] => suzuki 
	[2] => mghector 
	[3] => tata 
	[4] => nissan 
)

Example 3 :

<?php  
     $vehicle = array("a" => "mghector", "b" => "tata", "c" => "nissan");  
     array_push($vehicle, "hyundai", "suzuki", "mahindra");  
     print_r($vehicle);  
?>  

Output will be :

Array 
( 
	[a] => mghector 
	[b] => tata 
	 => nissan 
	[0] => hyundai 
	[1] => suzuki 
	[2] => mahindra 
)

Example 4 : In this I am not going to have the second array element :

<?php  
     $vehicle = array("a" => "mghector", "b" => "tata", "c" => "nissan");  
     array_push($vehicle);  
     print_r($vehicle);  
?>  

Output will be :

Array 
( 
	[a] => mghector 
	[b] => tata 
 => nissan 
)

In the previous post I described regarding the PHP Array Functions

Hope this article helps you in PHP development and understandings of Array. Stay tuned for more PHP Tutorials, Hope you enjoyed reading, if you need the professional PHP, PHP Framework and Magento 2 Development we can help you, just Click on the Link and send me your requirements.