How to Replace an Element Inside Array in PHP ?
Last Updated :
11 Jul, 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']
Here are some common approaches:
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;
// Display the updated array
print_r($arr);
?>
OutputArray
(
[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]);
// Display the modified array
print_r($modifiedArr);
?>
OutputArray
(
[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);
// Display the modified array
print_r($arr);
?>
OutputArray
(
[0] => 10
[1] => 100
[2] => 40
[3] => 50
[4] => 70
)
Approach 4: Using foreach Loop with Condition
In PHP, a foreach loop with a condition iterates through an array. Inside the loop, a condition (`if` statement) checks each element (`$value`) against a specified condition (`$value === 3`), allowing for targeted updates or operations based on element values.
Example: In this example we iterates through an array, replaces the first occurrence of the value 3 with 6, then stops further iteration.
PHP
<?php
$array = [1, 2, 3, 4, 5];
foreach ($array as $key => $value) {
if ($value === 3) {
$array[$key] = 6;
break; // Stop iterating once the condition is met
}
}
print_r($array); // Output: [1, 2, 6, 4, 5]
?>
OutputArray
(
[0] => 1
[1] => 2
[2] => 6
[3] => 4
[4] => 5
)
Approach 5: Using array_map() Function
The array_map() function applies a callback to the elements of the given arrays. It can be used to replace specific elements in an array by applying a custom function.
Example:
PHP
<?php
$arr = array(10, 30, 40, 50, 70);
$indexToReplace = 1;
$newValue = 100;
$modifiedArr = array_map(function($value, $key) use ($indexToReplace, $newValue) {
return ($key === $indexToReplace) ? $newValue : $value;
}, $arr, array_keys($arr));
// Display the modified array
print_r($modifiedArr);
?>
OutputArray
(
[0] => 10
[1] => 100
[2] => 40
[3] => 50
[4] => 70
)
Approach 5: Using array_search() and direct assignment
This approach uses array_search() to find the index of the element to replace and then directly assigns the new value to that index.
Example:
PHP
<?php
// Example array
$arr = [10, 20, 30, 40, 50];
// Find the index of the element to replace
$index = array_search(30, $arr);
if ($index !== false) {
// Replace the element at the found index
$arr[$index] = 100;
}
print_r($arr); // Output: [10, 20, 100, 40, 50]
?>
OutputArray
(
[0] => 10
[1] => 20
[2] => 100
[3] => 40
[4] => 50
)
Similar Reads
How to get elements in reverse order of an array in PHP ? An array is a collection of elements stored together. Every element in an array belong to a similar data type. The elements in the array are recognized by their index values. The elements can be subjected to a variety of operations, including reversal. There are various ways to reverse the elements
4 min read
How to Insert a New Element in an Array in PHP ? In PHP, an array is a type of data structure that allows us to store similar types of data under a single variable. The array is helpful to create a list of elements of similar types, which can be accessed using their index or key.We can insert an element or item in an array using the below function
5 min read
Removing Array Element and Re-Indexing in PHP In order to remove an element from an array, we can use unset() function which removes the element from an array, and then use array_values() function which indexes the array numerically automatically. Function Usedunset(): This function unsets a given variable. Syntax:void unset ( mixed $var [, mix
2 min read
How to find the index of an element in an array using PHP ? In this article, we will discuss how to find the index of an element in an array in PHP. Array indexing starts from 0 to n-1. Here we have some common approachesTable of ContentUsing array_search() FunctionUsing array_flip()Using a custom functionUsing a foreach LoopUsing array_keys FunctionUsing ar
6 min read
How to Slice an Array in PHP? In PHP, slicing an array means taking a subset of the array and extracting it according to designated indices. When you need to extract a subset of elements from an array without changing the original array, this operation comes in handy. PHP comes with a built-in function called array_slice() to he
2 min read
How to replace multiple characters in a string in PHP ? A string is a sequence of characters enclosed within single or double quotes. A string can also be looped through and modifications can be made to replace a particular sequence of characters in it. In this article, we will see how to replace multiple characters in a string in PHP.Using the str_repla
3 min read
How to delete an Element From an Array in PHP ? To delete an element from an array means to remove a specific value or item from the array, shifting subsequent elements to the left to fill the gap. This operation adjusts the array's length accordingly, eliminating the specified element.This article discusses some of the most common methods used i
4 min read
Remove First Element from an Array in PHP Given an array, the task is to remove the first element from an array in PHP. Examples:Input: arr = [1, 2, 3, 4, 5, 6, 7]; Output: 2, 3, 4, 5, 6, 7 Input: arr = [3, 4, 5, 6, 7, 1, 2] Output: 4, 5, 6, 7, 1, 2Below are the methods to remove the first element from an array in PHP:Table of ContentUsing
3 min read
How to check an element is exists in array or not in PHP ? An array may contain elements belonging to different data types, integer, character, or logical type. The values can then be inspected in the array using various in-built methods : Approach 1 (Using in_array() method): The array() method can be used to declare an array. The in_array() method in PHP
2 min read
How to reset Array in PHP ? You can reset array values or clear the values very easily in PHP. There are two methods to reset the array which are discussed further in this article. Methods: unset() Functionarray_diff() Function Method 1: unset() function: The unset() function is used to unset a specified variable or entire arr
2 min read