replace array value in php in non associative array,so that the output will be $arr = array(1,3,4,5); I want to replace today with 1.
How to replace 'today' with 1?
$arr = array('today',3,4,5);
replace array value in php in non associative array,so that the output will be $arr = array(1,3,4,5); I want to replace today with 1.
How to replace 'today' with 1?
$arr = array('today',3,4,5);
Find key of 'today' by array_search
$arr[array_search('today', $arr ,true )] = 1;
today value and 2.Only ever be just one today value, then this should be should be your accepted answer. This is because array_search() ceases to iterate the array as soon as the needle value is found. Viswanath's answer does not employ this "best practice". Though you are not required to, you can help future SO readers to find the best method by awarding the green tick to this answer. p.s. If either of #1 or #2 are not guaranteed, then a full-iteration method would be justifiable -- but I don't get this sense from your question.This should work for you:
First I filter all elements out, which aren't numeric with array_filter(). Then I get the keys from them with array_keys().
After this I array_combine() an array with the $keys and a range() from 1 to [as many keys you have].
At the end I just simply replace the keys which haven't a numeric value with the number of the $fill array with array_replace().
<?php
$arr = array('today', 3, 4, 5);
$keys = array_keys(array_filter($arr, function($v){
return !is_numeric($v);
}));
$fill = array_combine($keys, range(1, count($keys)));
$newArray = array_replace($arr, $fill);
print_r($newArray);
?>
output:
Array
(
[0] => 1
[1] => 3
[2] => 4
[3] => 5
)
You have to write like this code below
$arr = array('today', 3, 4, 5);
foreach ($arr as $key => $value) {
if ($value == 'today') {
$arr[$key] = 1;
}
}
Thanks