Php add element to array with index

Add Element Values to PHP Array: 5 Code Examples (2023)

There are several methods to add to an array in PHP. Using square brackets, array_push, and array_unshift function are the most common methods. The array_push & square brackets will add to the end of an array. You can add to associate arrays by setting a new key with values.

These methods differ in adding elements at different positions in an array. I have been used to array_push and use it most of the time to add multiple elements simultaneously.

By the end of this article, you’ll learn different ways of adding elements to an array.

Читайте также:  Html input box font style

Use Square Bracket Syntax to Add Values to PHP Arrays

The square bracket method is probably the most well-known method to add to an array in PHP. You can add individual elements by an integer, or a string index passed to the square brackets.

You can also empty the square brackets, and PHP will automatically add the elements to the next available index in the original array.

This method is preferable when adding a single element to the original array. It avoids the overhead of calling a function. However, for adding multiple values, this syntax could be daunting.

Square Bracket Method PHP Code Example

 Apple [1] => Orange [2] => Mango [3] => Watermelon [Vegetable] => Carrot [4] => Avocado ) */ ?> 

The code above covers all the possibilities to add to an array in PHP using this syntax. A remarkable feature is that PHP won’t throw an error even if you skip an index. The following code demonstrates this by skipping index 3.

 Apple [1] => Orange [2] => Mango [4] => Watermelon ) */ ?> 

Next, we’ll use the array_push array function to add one or more elements to a PHP array.

Use array_push Array Function to Add Element to End of Array

PHP’s array_push function adds elements to the end of the array. The great thing about array_push is that you can add any number of elements to the end of an array. I prefer this function whenever I need to add multiple elements at one go. It’s pretty simple to use.

Array Append PHP Code Example

 Apple [1] => Orange [2] => Mango [3] => Watermelon [4] => Avocado [5] => Strawberries ) */ ?> 

We see how easily we add three items at once through the array_push array function. The only concern using array_push is that it adds by integer index only.

Next, we’ll see array_unshift.

It is the opposite of array_push because it will insert into the beginning of the array elements.

Option 3: Add to the beginning of an array with array_unshift

While array_push adds to the end of an array, PHP’s array_unshift adds elements to the start of an array. You can add any number of elements, and the array will reindex the elements every time. Let’s demonstrate this through code.

PHP Add Item to Array Using array_unshift Code Example

 Watermelon [1] => Avocado [2] => Strawberries [3] => Apple [4] => Orange [5] => Mango ) */ ?> 

See how neatly it adds the elements and reindexes the array. Next, we see array_splice which can add elements to an array at any specified index.

Option 4: Replace and add new items to the array with the array_splice

PHP’s array_splice is mainly used for removing and replacing elements in an array. It creates a new array based on the content of the old array.

However, there is a neat trick if you want to add to an array using this function. First, let’s understand the function and its arguments as specified in the official documentation.

array_splice(array,start,length,value)
  • array – Input array (Required)
  • start – The offset value for specifying where the function should start replacing values.
  • length – Specifies the number of elements to be replaced.
  • value A replacement of the removed values from the array.

Passing zero to the length argument doesn’t remove elements from the array but adds at the specified start value. The array_splice function is robust because it can add elements at any position in an array, unlike array_push and array_unshift.

1. Adding at the middle of an array

The code here adds in the middle of an array at index 2. We specify an offset value of 2 and the function adds the elements at that position.

 Apple [1] => Orange [2] => Avocado [3] => Strawberries [4] => Mango [5] => Watermelon ) */ ?> 

Add element values to the start of an array

That’s how we can add to the start of an array using array_splice. A start value of zero sets the offset to the beginning of the array.

 Avocado [1] => Strawberries [2] => Apple [3] => Orange [4] => Mango [5] => Watermelon ) */ ?> 

Add array values to the end

Passing -1 to the start arguments sets the offset to the end of the array. However, the function adds elements all the way up from the second-last index position.

 Apple [1] => Orange [2] => Mango [3] => Avocado [4] => Strawberries [5] => Watermelon ) */ ?> 

That’s all about the different methods to add to an array in PHP. We hope that you’ve enjoyed the article.

When to Use array_push vs Square Brackets to Append PHP Array

You will generally use the square brackets whenever needing to add single elements to arrays. It is more concise and has better performance (for larger arrays). On the other hand, array_push is the correct method when adding multiple values to an array.

  1. Readability: Both methods are easy to understand, but square brackets are more concise and often considered more readable for appending single elements.
  2. Performance: The square bracket method is generally faster than the array_push function, especially for large arrays, as the latter has the overhead of a function call. However, the performance difference is negligible for small arrays.
  3. Flexibility: array_push() You can add multiple elements simultaneously, while square brackets must be used multiple times to add more than one element. This can make array_push() more convenient when dealing with multiple values.

Best Practices:

  1. Use square brackets when adding a single element to an array, as it is more concise and performs better.
  2. If you need to add multiple elements, consider using array_push() for improved readability.
  3. Always consider the performance implications of each method when dealing with large arrays, as using the most efficient approach can improve the performance of your PHP application.

Want to explore further about PHP arrays?

We have many fun articles related to PHP arrays. You can explore these for learning more about arrays in PHP.

Источник

Php add element to array with index

// 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 Program to insert element into an array at specified index

Tutorial Study Image

Arrays are one of the data structures in PHP. An array is used to store the same type of data in a contiguous memory location. We can store any amount of data in the array. The “array ()” function is used to create an array in PHP.

How to insert an element into the array at a certain position using PHP?

To insert an element into an array we need an index or position where it is to be placed because elements are fetched using array index only. To add an element to the end of an array is easy but we need shifting of elements to insert an element in between of array. PHP provides an in-built function array_splice() to insert elements, let’s make use of it in our program.

In this program, we are going to insert an element at a specified index. For that, we first declare and assign values into the array arr[]. After that, we need a new value that is going to insert into the array and assign a value to the variable newValue. Then we have to specify the position where we have to insert the new element and assign that value to the variable pos. And to insert the element we are using the built-in function array_splice() . In the function, we specify the array arr[], the position of the element in variable pos, and the newValue. And at last, we can print the elements of the array arr[] by using foreach loop .

Syntax of array_splice() function

 array_splice(src_array, start_index, length, replace_array) 

The array_splice() function removes selected elements of size length from start_index of an array src_array and replaces them with new elements given in replace_array . The function also returns an array with the removed elements.

NOTE: If the length= 0 t hen the function does not remove any array elements instead the replace_array element will be inserted from the start_index position.

It is a simple array program in PHP using an array, loop, and in-built function. Let’s go through these topics to understand this program clearly»

ALGORITHM

Step 1: Initialize an array arr[] with values

Step 2: Print the element currently in the array arr[] using foreach loop

Step 3: Assign the new value to be inserted to the variable newValue

Step 4: Assign the position of the element to be inserted into the variable pos

Step 5: Call the built-in function array_splice(arr, pos,0,newValue)

Step 6: Print the elements in the array arr[] using foreach loop

PHP Source Code

 $newValue = 23; $pos = 2; array_splice($arr, $pos, 0, $newValue); echo "\nArray after inserting new element: \n"; foreach ($arr as $x) < echo "$x "; >?> 

OUTPUT

Array before inserting new element: 1 2 3 4 5 Array after inserting new element: 1 2 23 3 4 5

Источник

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