Adding items to array php

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.

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.

Читайте также:  Profile image upload in php

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.

Источник

Adding items to array php

// Before php 5.4
$array = array(1,2,3);

// since php 5.4 , short syntax
$array = [1,2,3];

// I recommend using the short syntax if you have php version >= 5.4

Used to creating arrays like this in Perl?

Looks like we need the range() function in PHP:

$array = array_merge (array( ‘All’ ), range ( ‘A’ , ‘Z’ ));
?>

You don’t need to array_merge if it’s just one range:

There is another kind of array (php>= 5.3.0) produced by

$array = new SplFixedArray(5);

Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation.

Supposing a large string-keyed array

$arr=[‘string1’=>$data1, ‘string2’=>$data2 etc. ]

when getting the keyed data with

php does *not* have to search through the array comparing each key string to the given key (‘string1’) one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it’s all hidden away.

However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :

Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It’s also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).

When creating arrays , if we have an element with the same value as another element from the same array, we would expect PHP instead of creating new zval container to increase the refcount and point the duplicate symbol to the same zval. This is true except for value type integer.
Example:

$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => 23 ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=0, is_ref=0)int 23

but :
$arr = [‘bebe’ => ‘Bob’, ‘age’ => 23, ‘too’ => ’23’ ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=0, is_ref=0)int 23
‘too’ => (refcount=1, is_ref=0)string ’23’ (length=2)
or :

$arr = [‘bebe’ => ‘Bob’, ‘age’ => [1,2], ‘too’ => [1,2] ];
xdebug_debug_zval( ‘arr’ );

(refcount=2, is_ref=0)
array (size=3)
‘bebe’ => (refcount=1, is_ref=0)string ‘Bob’ (length=3)
‘age’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2
‘too’ => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2

This function makes (assoc.) array creation much easier:

function arr (. $array )< return $array ; >
?>

It allows for short syntax like:

$arr = arr ( x : 1 , y : 2 , z : 3 );
?>

Instead of:

$arr = [ «x» => 1 , «y» => 2 , «z» => 3 ];
// or
$arr2 = array( «x» => 1 , «y» => 2 , «z» => 3 );
?>

Sadly PHP 8.2 doesn’t support this named arguments in the «array» function/language construct.

Источник

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.

Источник

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