PHP array_push() function
In this chapter you will learn:
- Syntax for PHP array_push() function
- Definition for PHP array_push() function
- Parameter for PHP array_push() function
- Note for PHP array_push() function
- Note 2 for PHP array_push() function
- Example - Push element to an array
- Example - Push more than one value to an array
Syntax
PHP array_push() function has the following syntax.
int array_push ( array &arr, mixed var [, mixed ...] )
Definition
The array_push()
function pushes value onto the end of an array.
This is the opposite of the array_pop()
function:
Parameter
Parameter | Is Required | Description |
---|---|---|
array | Required. | Array to push |
value1 | Required. | Value to add |
value2 | Optional. | Value to add |
Note
To add an element to the end of an array, we can use the square bracket syntax.
Or we can use array_push(), which allows us to add multiple elements at once and also tells us the new length of the array.
Note 2
With both array_unshift() and array_push(), if you include an array as one of the values to add, the array is added to the original array as an element, and the original array become a multidimensional array:
<?PHP/*from ja v a 2 s .c om*/
$authors = array( "Java", "PHP", "CSS", "HTML" );
$newAuthors = array( "Javascript", "Python" );
echo array_push( $authors, $newAuthors ) . "\n";
print_r( $authors );
?>
If you instead want to add the elements of the array individually to the original array, use array_merge().
The code above generates the following result.
Example 1
Push element to an array
<?PHP// j a va2s.c o m
$firstname = "java2s.com";
$names = array("PHP", "Java", "C#", "HTML", "CSS");
array_push($names, $firstname);
print_r($names);
?>
The code above generates the following result.
Example 2
You use array_push in much the same way as array_unshift(): pass the array, followed by the value(s) to add.
<?PHP/*j av a 2 s . c o m*/
$authors = array( "Java", "PHP", "CSS", "HTML" );
echo array_push( $authors, "Javascript", "Python" ) . "\n";
print_r( $authors );
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP array_rand() function
- Syntax for PHP array_rand() function
- Parameter for PHP array_rand() function
- Example - Get random values from an array