Php add to array function

How to add elements to an array in PHP?

In this short tutorial, we look at how to add PHP elements to an array, the different methods to do so, and their use-cases.

However, in case you are here only for the solution use this link.

Table of Contents — PHP add to array

PHP: Add to array or append to array:

Appending or adding an element into an array is a commonly used method not only in PHP but in other programming languages as well. However, adding elements to an array in PHP can be done with a handful of methods.

These methods vary based on their use cases. If you are looking to add an element at the end of the array, you can look at the two methods.

Читайте также:  Php write warnings to file

If you are looking to add elements to the beginning of the array, the array_unshift method can be used.

Add to array using square brackets:

The square bracket method to PHP add to array is one of the most commonly used methods.

Because of its efficiency, most programmers recommend the use of this method. In comparison to the other methods, it adds to an array without the overhead of calling a function.

But the downside is that it can only add one argument at a time.

Syntax of Square Bracket method

Here array refers to the original array you are looking to append.

element is the value you are looking to add to the array.

Code and Explanation

$skillset= array( 'JavaScript', 'Python', 'C++' ); //Now, let's add to the array $skillset[] = 'PHP'; //Output var_dump($skillset);

Output

array(4) < [0]=>string(10) "Javascript" [1]=> string(6) "Python" [2]=> string(3) "C++" [3]=> string(3) "PHP" >

As you can see, the above code can be used in PHP to add to array. But despite its efficiency, adding more than one element would be a hassle while using this method.

Using the array_push method:

The array_push is another inbuilt function that can be used in PHP to add to arrays. This method can be used to add multiple elements to an array at once.

Syntax of array_push

array_push($array , value1, value2, . value(n-1))

Parameters:

array — Required, this parameter specifies the array you are looking to append

value1 — The value that you are looking to add to the array

Return Values

The array_push returns the number of elements in the array.

Code and Explanation:

$skillset= array( 'JavaScript', 'Python', 'C++' ); //Now, let's add to the array array_push($skillset, 'PHP', 'HTML', 'CSS'); var_dump($skillset);

Output

array(6) < [0]=>string(10) "Javascript" [1]=> string(6) "Python" [2]=> string(3) "C++" [3]=> string(3) "PHP" [4]=> string(4) "HTML" [5]=> string(3) "CSS" >

As you can see the array_push in PHP adds to array the passed elements.

However, It is important to remember that the function returns the length and not the appended array. This is important because assigning the function to a variable and printing it would not return your desired output.

The below code explains the same.

$skillset= array( 'JavaScript', 'Python', 'C++' ); //Now, let's add to the array $new_array = array_push($skillset, 'PHP', 'HTML', 'CSS'); echo($new_array);

This code outputs 6 which is the length of the updated array that you desired.

PHP: Add to array — Limitations and Caveats:

  • Remember that the square bracket is more efficient and should always be chosen when you are looking to add to an array.
  • While using the square bracket method, ensure that the name of the existing array is entered correctly because if the name passed is wrong a new array would be created.
  • The array_push returns a warning when the array you are looking to add to does not exist.

We work with skilled PHP developers to build amazing products. Do check out our services.

Источник

PHP array_push() Function

The array_push() function inserts one or more elements to the end of an array.

Tip: You can add one value, or as many as you like.

Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).

Syntax

Parameter Values

Parameter Description
array Required. Specifies an array
value1 Optional. Specifies the value to add (Required in PHP versions before 7.3)
value2 Optional. Specifies the value to add

Technical Details

Return Value: Returns the new number of elements in the array
PHP Version: 4+
Change log: As of version 7.3 this function can be called with only the array parameter

More Examples

Example

An array with string keys:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

PHP: array_push Function | PHP Add to Array Tutorial

Today, we will talk about an array function in PHP called array_push which is used to push elements into an array.

We will learn:

  • How to add single item to array in php
  • How to add multiple items to array in php
  • How to push array inside array in php

Understanding array_push function

The array_push() is used to insert new elements at the end of given array. It can accept any numbers of elements to be pushed at the end of the array. Let’s see an example:

Syntax

array_push( array &$array, $value1, $value2 . .)
  1. The array_push() function accepts array as the first argument [Required and array type]
  2. The second parameter ($value1) can be any value to be pushed to the end of the array [Required]
  3. Third and subsequent parameters are optional and defines the next values to be pushed to the array [Optional]

Example

$num = ['one','two', 'three']; array_push($num, 'four', 'five'); print_r($num); // ['one','two', 'three','four', 'five']

Let’s review some different use-cases where you would need to use array_push() function to add items to an array:

Adding single item to an array

Most basic use-case is to add just one element to an array in php. For that, you can use array_push() function as below:

$flowers = ['lily','rose']; array_push($flowers, 'sunflower'); print_r($flowers); // ['lily', 'rose', 'sunflower']

if you just want to add single item to an array then you don’t need to use array_push() function as there is more efficient way to push single item to an array:

$flowers = ['lily', 'rose']; $flowers[] = 'sunflower'; print_r($flowers); // ['lily', 'rose', 'sunflower']

Using [] operator to push single item to an array is more efficient as there is no overhead of calling a function.

Adding multiple items to an array

If you want to push multiple elements to an array, then array_push() is perfect function for that. It will append all items to the end of an array in the order you passed. Let’s check out an example:

$flowers = ['lily', 'rose']; array_push($flowers, 'sunflower', 'orchid'); print_r($flowers); // ['lily', 'rose', 'sunflower', 'orchid']

Adding array to an array

You can also pass an array inside an array. An array can still be a value, right?

$flowers = ['lily', 'rose']; array_push($flowers, ['name' => 'sunflower', 'type' => 'flower']); print_r($flowers); // output [ 0 => 'lily', 1 => 'rose', 2 => [ 'name' => 'sunflower', 'type' => 'flower' ] ]

Here, at 3rd index, whole array has been assigned. Thus, in PHP array, you can mix-match different types of values including arrays.

Adding an item to multidimensional array

In previous section, we learnt how to push an array inside another array. What if you want to add an item to the inner array? That’s actually called multi-dimensional array.

Let’s see how we can add item to multi-dimensional array:

$marray = [4,5,['one','two'] ]; //let's add an item to sunflower array array_push($marray[2], 'three', 'four']; print_r($marray); //output [ 4, 5, ['one', 'two', 'three', 'four'] ]

Pushing key and value in Associative array

The array_push() doesn’t support setting key for the value to be added therefore you cannot use it to pass key⇒value item to an array in. Instead, we will use [] operator:

$user = ['name' => 'John Doe', 'email' => 'john@example.com']; $user['type'] = 'admin'; $user['status'] = 'active'; print_r($user); //output [ 'name' => 'John Doe', 'email' => 'john@example.com' 'type' => 'admin', 'status' => 'active' ]

Thus, you can add an item with key in associative array by pushing via []. Similarly, you can push key⇒value item to multi-dimensional array too (which makes sense tbh)

Hope, this tutorial helped you get quick understand of array_push() function as well as helped you in several use-cases of pushing items to array in PHP.

Источник

Оцените статью