在非关联数组中替换php中的数组值

在非关联数组中替换php中的数组值

问题描述:

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);

在非关联数组中替换php中的数组值,以便输出 $ arr = array( 1,3,4,5); code>我想今天用1替换。 p>

如何用1代替'今天'? p> $ arr = array('today',3,4,5); code> pre> div>

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

Find key of 'today' by array_search

$arr[array_search('today', $arr ,true )] = 1;

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
)