0

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);
2
  • 1. Have you tried something ? 2. Why 1? and not 0 or 2 ? Commented Jul 8, 2015 at 8:35
  • It is my requirement,i want to replace 'today' with given value Commented Jul 8, 2015 at 8:36

3 Answers 3

2

Find key of 'today' by array_search

$arr[array_search('today', $arr ,true )] = 1;
Sign up to request clarification or add additional context in comments.

1 Comment

@Manoj If you know that there will: 1. Always be a 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.
2

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
)

Comments

0

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

1 Comment

@Manoj I think a more inflexible solution you couldn't get

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.