How to insert array value in php

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

  • Array in PHP
  • Loops in PHP
  • Output methods of PHP

What is an array and how to insert elements to it?

An array is a data structure consisting of a collection of elements, each identified by at least one array index or key. The Elements are of the same data type.

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 to insert elements, let's make use of it in our program.

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

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, assign a value into the variable newValue. Then we have to specify the position where we have to insert the new element and assign that value into 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: The function does not remove any elements (if length= 0), the replace_array will be inserted from the position of the start_index parameter.

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

                                          <?php
$arr = array(1, 2, 3, 4, 5);
echo "Array before inserting new element: \n";
foreach ($arr as $x) {
    echo "$x ";
}
$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

How to insert array value in php

PHP add to array is an operation in which we append elements to the existing array. An array can contain many values under a single name, and you can access the values by referring to an index number.

In PHP, there are three types of array.

  1. Indexed arrays – Arrays with the numeric index.
  2. Associative arrays – Arrays with the named keys.
  3. Multidimensional arrays – Arrays that contain one or more arrays.

Now, let’s see an example where we perform PHP to add array operations.

PHP array_push() is a built-in function used to insert new elements at the end of an array and get the updated array elements. The array_push() method takes a single element or an array of elements and appends it to the array.

You may add as many values as you need. Your inserted elements will always have numeric keys, even if the array itself has string keys. PHP array push() function has been introduced in PHP 4.

If we want to add more values to a PHP array, we need to use the array_push() function, which inserts one or more elements to the end of an array.

The length of the array increases by the number of variables pushed. You can add one element or multiple elements at a time using the array_push() function.

The array_push() treats an array as a stack and pushes the passed variables onto an array’s end. 

Syntax

The syntax for PHP Array Push is the following.

array_push(array,value1,value2...)

Parameters

An array parameter is required in which we will add the value.

The value1 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 need to pass those parameters if we want to add multiple values.

Return value

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

Example

Let’s see an example.

Create one file called app.php and add the following code.

<?php

// app.php

$netflix = ['Stranger Things', 'Black Mirror', 'Bright', 'XOXO'];

$new = array_push($netflix, 'Shaft');

print_r($netflix);
echo $new."\n";

In the above code, we have defined one array called $netflix, which has four items.

We have added the fifth item using the array_push() function in PHP and then printed the original array and the return value from the array_push function.

Now, we are running the file on the terminal. So go to the terminal, navigate the app.php file directory, and type the following command to run the file.

php app.php

See the output.

How to insert array value in php

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

Also, 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.

Adding multiple values to PHP array

To add multiple values in PHP array, 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.

<?php

// app.php

$netflix = ['Stranger Things', 'Black Mirror', 'Bright', 'XOXO'];

$new = array_push($netflix, 'Shaft', 'Mute', 'Clinical', 'Blue Jay', 'Candy Jar');

print_r($netflix);
echo $new."\n";

The output is the following.

How to insert array value in php

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.

Let’s take a scenario where we add values to the Associative Array.

<?php

// app.php

$data = ['name' => 'Krunal', 'education' => 'BE'];
$new = array_push($data, 'Ankit', 'MCA');

print_r($data);
echo $new."\n";

See, the $data variable is 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 3rd and 4th, they have indexes starting from 0. So, let’s run the PHP file and see the output.

How to insert array value in php

Adding 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.

Okay, now let’s take a scenario where we add a whole array inside an array and see the output.

<?php

// app.php

$dataA = ['name' => 'Krunal', 'education' => 'BE'];
$second = ['Facebook', 'Instagram'];
$newA = array_push($dataA, $second);

print_r($dataA);
echo $newA."\n";

The output is the following.

How to insert array value in php

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

So, right now, the dataA array is a multidimensional array.

PHP array length

To check array length in PHP, use the count() function. The count() method returns the total number of elements in the array. The sizeof() is an alias of the master function count().

<?php

$netflix = ['Stranger Things', 'Black Mirror', 'Bright', 'XOXO'];

echo count($netflix);

See the following output.

➜  pro php app.php
4                                                                               
➜  pro

That means we have four elements in the $netflix array. If we add more items inside the array, then the size of the array increases, and if we use the array_pop() function, it will decrease the array length by one.

Pushing key and value in Associative Array

There is no array_push() equivalent for associative arrays because there is no way to determine the next key. We can use the array_push() method, but adding the index starts from 0 and 1, not the keys we desire. So if you want to push key and value, you can do the following code.

<?php

$data = ['name' => 'Krunal', 'education' => 'BE']; 

$data['age'] = 26;
$data['business'] = 'IT';
print_r($data);

Output

Array
(
    [name] => Krunal
    [education] => BE
    [age] => 26
    [business] => IT
)

In the output, you can see that, and we can add multiple keys of your choice and not the ones that numeric keys php provides by default.

Pushing a value into the array automatically creates a numeric key for it. Therefore, when inserting a key-value pair to the array, you already have the key, and you don’t need one to be created for you. That key is the numeric key, which starts from 0.

Adding 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.

<?php

$data = ['Python', 'Javascript', 'Golang'];
array_unshift($data, 'PHP');
print_r($data);

Output

Array
(
    [0] => PHP
    [1] => Python
    [2] => Javascript
    [3] => Golang
)

You can see that our new element “PHP” is added at the index position 0. 

The array_unshift() function adds new elements to the array. The new array values will be inserted at the beginning of the array. You can insert one value or as many as you like. Numeric keys will start at 0 and increase by 1 every time a new element is added. String keys will remain the same.

That’s it for PHP array_push() function.

PHP array_product()

PHP array_reverse()

PHP array_sum()

PHP array_walk()

PHP array_replace()

How do you data insert in array in PHP?

The following code will help to create a PHP function to insert array PHP data into MySQL. For Ex. We have the following PHP array. $records = array( "0" => array("Parvez", "PHP", "12"), "1" => array("Devid", "Java", "34"), "2" => array("Ajay", "Nodejs", "22") );

Can you add to an array in PHP?

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.

How do you add a variable value to an array?

Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.

What is array values in PHP?

The array_values() is an inbuilt PHP function is used to get an array of values from another array that may contain key-value pairs or just values. The function creates another array where it stores all the values and by default assigns numerical keys to the values.