How to Replace an Element Inside Array in PHP ?
Last Updated :
02 Jan, 2024
Given an array containing some elements, the task is to replace an element inside the array in PHP. There are various methods to manipulate arrays, including replacing elements.
Examples:
Input: arr = [10, 20, 30, 40, 50], index_1 = 100
Output: [10, 100, 30, 40, 50]
Input: arr = ['GFG', 'Geeks', 'Hello'], index_2 = 'Welcome'
Output: ['GFG', 'Geeks', 'Welcome']
Approach 1: Using Index Assignment
The most straightforward way to replace an element in a PHP array is to directly assign a new value to the desired index.
PHP
<?php
$arr = array (10, 30, 40, 50, 70);
$arr [1] = 100;
print_r( $arr );
?>
|
Output
Array
(
[0] => 10
[1] => 100
[2] => 40
[3] => 50
[4] => 70
)
Approach 2: Using array_replace() Function
PHP provides the array_replace() function that merges the values of two or more arrays. It is particularly useful for replacing specific elements.
PHP
<?php
$arr = array (10, 30, 40, 50, 70);
$modifiedArr = array_replace( $arr , [1 => 100]);
print_r( $modifiedArr );
?>
|
Output
Array
(
[0] => 10
[1] => 100
[2] => 40
[3] => 50
[4] => 70
)
Approach 3: Using array_splice() Function
The array_splice() function allows us to remove a portion of the array and replace it with new elements.
PHP
<?php
$arr = array (10, 30, 40, 50, 70);
array_splice ( $arr , 1, 1, 100);
print_r( $arr );
?>
|
Output
Array
(
[0] => 10
[1] => 100
[2] => 40
[3] => 50
[4] => 70
)
Share your thoughts in the comments
Please Login to comment...