w3resource

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

PHP Array: Exercise-7 with Solution

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

Sample Solution:

PHP Code:

<?php
$original = array( '1','2','3','4','5' );
echo 'Original array : '."\n";
foreach ($original as $x) 
{echo "$x ";}
$inserted = '$';
array_splice( $original, 3, 0, $inserted ); 
echo " \n After inserting '$' the array is : "."\n";
foreach ($original as $x) 
{echo "$x ";}
echo "\n"
?>

Sample 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

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP script which decodes the specified JSON string.
Next: Write a PHP script to sort the specified associative array

What is the difficulty level of this exercise?



PHP: Tips of the Day

PHP: Extract numbers from a string

$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);