Home > Article > Backend Development > How to replace a value in an array in php
Replacement steps: 1. Use "array_values($arr)" to convert the specified array into an index array; 2. Use "array_search("specified value", index array)" to search for values and return the corresponding index value; 3. Replace with "array_splice($arr,index,1,"replacement value")".
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
php in the replacement array Method of a value
Step 1. Use array_values() to convert the specified array into an index array
<?php header('content-type:text/html;charset=utf-8'); $arr=array("a"=>"red","b"=>"green","c"=>"blue"); $values=array_values($arr); var_dump($values); ?>
Step 2. Use array_search() to search for the specified value and return the corresponding index value (key name)
array_search() function searches for a certain key value in the array, and Return the corresponding key name.
$index=array_search("green",$values); echo $index;
Step 3. Use array_splice() to replace the array value according to the index value.
array_splice($arr, $index, 1, "orange"); var_dump($arr);
Description: array_splice() function
array_splice() function is used to delete some elements of the array; you It can be deleted directly or replaced with other values.
array_splice() syntax is as follows:
array array_splice ( array &$arr, int $start [, int $length = 0 [, mixed $replacement ]] )
Parameter description:
If the combination of start and length results in no element being deleted, then the value contained in replacement will be inserted into the position specified by start.
Note that using replacement to replace array elements will not retain the original key names.
Return value: Returns an array consisting of the deleted elements.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to replace a value in an array in php. For more information, please follow other related articles on the PHP Chinese website!