w3resource

PHP Array Exercises : Inserts a new item in an array in any position


7. Insert New Array Item by Position

Write a PHP script that inserts a new item in an array in any position.

Sample Solution:

PHP Code:

<?php
// Define an indexed array $original with elements '1', '2', '3', '4', '5'
$original = array( '1', '2', '3', '4', '5' );

// Output a message indicating the original array
echo 'Original array : ' . "\n";

// Iterate through the elements of the original array and echo them
foreach ($original as $x) {
    echo "$x ";
}

// Define a string '$' to be inserted into the array
$inserted = '$';

// Use array_splice() to insert the value '$' at index 3 in the original array
array_splice($original, 3, 0, $inserted);

// Output a message indicating the array after the insertion
echo " \n After inserting '$' the array is : " . "\n";

// Iterate through the modified array and echo its elements
foreach ($original as $x) {
    echo "$x ";
}

// Output a newline character for better formatting
echo "\n";
?>

Output:

Original array :                                            
1 2 3 4 5                                                   
 After inserting '$' the array is :                         
1 2 3 $ 4 5   

Flowchart:

Flowchart: Inserts a new item in an array in any position

For more Practice: Solve these Related Problems:

  • Write a PHP script to insert an element into the middle of an indexed array and then print the modified array.
  • Write a PHP function to insert a given value at a specified index in an array and return the updated array.
  • Write a PHP program to add an element into an array without overwriting any current elements, using array_splice().
  • Write a PHP script to insert multiple new items at different positions in an array and then display the final array.

Go to:


PREV : Decode JSON String.
NEXT : Sort Associative Array by Key and Value.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.