Manoj
Manoj

Reputation: 3

replace array value in php in non associative array

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

Upvotes: 0

Views: 361

Answers (3)

Rizier123
Rizier123

Reputation: 59701

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
)

Upvotes: 2

splash58
splash58

Reputation: 26153

Find key of 'today' by array_search

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

Upvotes: 2

Viswanath Polaki
Viswanath Polaki

Reputation: 1402

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

Upvotes: 0

Related Questions