Add all items in array php

PHP array_push() Function: How to Add Elements to an Array

PHP array_push() function is “used to push new elements into an array.” The array_push() method takes a single element or an array of elements and appends it to the array.

Syntax

array_push(array,value1,value2. ) 

Parameters

  1. array: This parameter is required to which we will add the value.
  2. value1: This parameter is also required, which is the value we will insert into the specified array. The value2, value3, and so on are optional parameters. However, we must pass those parameters to add multiple values.

Return value

The array_push() function will return the length of new elements of an array.

Example 1: Implementation of array_push() method

 $netflix = ['Stranger Things', 'Black Mirror', 'Bright', 'XOXO']; $new = array_push($netflix, 'Shaft'); print_r($netflix); echo $new."\n";

PHP Array Push Example | Add Elements To An Array

That means we have successfully added the Shaft show to the $neflix array.

The array_push() function returns the length of the array. In our case, it is 5. Remember, the PHP Array index starts from 0.

This operation is also called PHP add to the array.

Example 2: Adding multiple values to the PHP array

To add multiple values in the PHP array, you can use the array_push() function.

The array_push() function takes multiple elements and appends all the elements into the array.

It will add in the order that they are added. It does not change its order.

 $netflix = ['Stranger Things', 'Black Mirror', 'Bright', 'XOXO']; $new = array_push($netflix, 'Shaft', 'Mute', 'Clinical', 'Blue Jay', 'Candy Jar'); print_r($netflix); echo $new."\n";

Add Multiple Values To An Array in PHP

Example 3: Adding values to the Associative Array

To add values in an associative array in PHP, use the array_push() function. The array_push() function takes single or multiple arguments and returns the associative array.

 $data = ['name' => 'Krunal', 'education' => 'BE']; $new = array_push($data, 'Ankit', 'MCA'); print_r($data); echo $new."\n";

The $data variable is an Associative Array, and we have added two values to that array.

That means the first two items are associative, which have their key. But, from the 3rd and 4th, they have indexes starting from 0.

So, let’s run the PHP file and see the output.

Add Values to the Associative Array in PHP

Example 4: Adding an array into an array in PHP

To add an array into an array in PHP, use the array_push() function. The array_push() function takes an array as an argument and returns the array combining with old and new values.

 $dataA = ['name' => 'Krunal', 'education' => 'BE']; $second = ['Facebook', 'Instagram']; $newA = array_push($dataA, $second); print_r($dataA); echo $newA."\n"; 

Add Array in the Array

See, it has added an array as a 3rd element, and its index is 0 and 1.

Right now, the dataA array is a multidimensional array.

Example 5: Pushing key and value in Associative Array

 $data = ['name' => 'Krunal', 'education' => 'BE']; $data['age'] = 26; $data['business'] = 'IT'; print_r($data); 
Array ( [name] => Krunal [education] => BE [age] => 26 [business] => IT )

Example 6: Adding an element at the start of the Array

To add an element at the start of the array, you can use the PHP array_unshift() function. It appends the item at the beginning of the array at the index of 0.

 $data = ['Python', 'Javascript', 'Golang']; array_unshift($data, 'PHP'); print_r($data); 
Array ( [0] => PHP [1] => Python [2] => Javascript [3] => Golang ) 

Example 7: Append elements using square brackets syntax in PHP

If you are using PHP version 5.4 or higher, you can use the square bracket syntax to add elements to an array like this:

$phones[] = 'iphone'; $phones[] = 'galaxy';

Источник

Add all items in 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.

Источник

How do you push multiple items to array PHP

There are 2 ways to add multiple elements to a PHP array. You can use the spread method or use the array_merge function. Check out the article for examples.

Push multiple items to array PHP

PHP arrays are dynamic, thus extendable at run time. It means that you can push multiple items to array PHP, and it won’t bother you with exceptions like a static array would in Java or C++. PHP array_push function is super helpful in pushing into an array though iteration also works.

This article includes examples of pushing multiple items to an array. The first example uses a loop, followed by other examples of using array_push and array_merge. So, let’s just get to the examples now.

Push multiple items to array PHP with loop

We have an array of numbers from six to ten, and we need to push these to an array that already has numbers from one to five. The following example adds items iteratively to an array in PHP.

 /* OUTPUT [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] */ ?> 

So, $numbers[] syntax tells PHP to push $nums into it. The loop pushes numbers from six to ten iteratively. In this way, we push multiple items to array PHP.

Quick Note

PHP array_push pushes one or more elements to an array. Use array_push when there multiple elements to push. Use the example syntax for a single element push to avoid the overhead of a function call.

Push multiple items to array PHP with array_push

PHP array_push pushes one or more items to an array. Following is the function signature of array_push.

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

So, the function takes an input array as an argument followed by items that we need to push into the input array. A comma separates these items, as the following example shows.

 /* OUTPUT [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] */ ?> 

You can see that nothing has changed so far. The example looks pretty similar to the previous one except that we’re using array_push now. Pushing the whole array means adding an array within an array. Luckily, there’s a solution – the “Spread Operator.”

Push multiple items to array PHP with spread operator

PHP 7.4 introduced the “Spread Operator.” PHP uses three dots syntax for spread operation. Just prefix an array with three dots, and PHP spreads the elements in place. This operation applies to the examples we have seen already.

Voila! The example reduces to one function call. That’s the power of the spread operator. It lets you push multiple items to array PHP without using any loop explicitly.

Push multiple items to array PHP using array_merge

PHP array_merge is another way to push multiple items to array PHP. The function has some caveats that you can read by following the link. Here we’ll see it through an example.

Perfect! All done in one call. Also, the spread operator tends to be faster than the array_merge, and this is obvious because the spread operator is a PHP construct rather than a function. They work differently under the hood.

Push multiple items to an associative array in PHP

The associative array has keys and values. Unfortunately, the spread operator doesn’t work with string keys and raises an exception. So, we are left with either the good old loop way or the array_merge.

The array_merge is just a function call, demonstrating the loop example here.

 10, 'Shaun' => 11, 'Robert' => 15]; $some_more_scores = ['Ron' => 18, 'Kylie' => 22]; foreach($some_more_scores as $k => $v) < $scores[$k] = $v; >/* OUTPUT Array ( [Adam] => 10 [Shaun] => 11 [Robert] => 15 [Ron] => 18 [Kylie] => 22 ) */ ?> 

Voila! The example creates a key and assigns it a value iteratively in a loop.

Conclusion

This article includes examples of pushing multiple items to array PHP using a loop or the spread operator. The spread operator syntax is more compact and cleaner than using a loop. The foreach loop is faster than the spread operator, but that doesn’t matter much in trivial cases. So, what option would you pick?

That’s all for the article. We hope you liked it. To see more articles and tutorials about PHP, stay tuned to FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

Источник

Читайте также:  Html meta refresh one time
Оцените статью