Replacing a value inside array

Discussion in 'PHP' started by Shadow, Mar 13, 2006.

  1. #1
    That's driving me nuts, can't figure it out.

    $input = array("red", "green", "blue", "yellow");
    Code (markup):
    Trying to replace green with apple.

    EDIT:

    Seriously, I've been looking into array_slice for at least 15 minutes and it just didn't work. Well, now I figured it out. Sorry again for the waste of bandwidth :eek:
     
    Shadow, Mar 13, 2006 IP
  2. sketch

    sketch Well-Known Member

    Messages:
    898
    Likes Received:
    26
    Best Answers:
    0
    Trophy Points:
    148
    #2
    I don't think there's a PHP function to simply replace a value with another value. Values have to be modified or assigned. All array_slice does is return the values of an array between the first and second parameters.

    I think this is the shortest way...

    $green_key = array_search('green', $input); // returns the first key whose value is 'green'
    $input[$green_key] = 'apple'; // replace 'green' with 'apple'
    PHP:
    Technically, simply going $input[1] = 'apple' would work if 'green' is always in the second spot :p
     
    sketch, Mar 13, 2006 IP
  3. adstracker

    adstracker Peon

    Messages:
    81
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Or:

    
    <?php
    $input = array("red", "green", "blue", "yellow");
    $needle = "green";
    $replacement = "apple";
    for($i=0;$i<count($input);$i++) {
       if($input[$i] == $needle) {
       $input[$i] = $replacement;
       }
    }
    ?>
    
    PHP:
    Array_search is pretty heavy on the server load, ( increases parse time ), so i tend to use loops more.
     
    adstracker, Mar 13, 2006 IP
    Shadow likes this.
  4. Shadow

    Shadow Peon

    Messages:
    191
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Yes, definitely a great way to do it. Gonna use that instead of array_slice. Thank You
     
    Shadow, Mar 13, 2006 IP
  5. adstracker

    adstracker Peon

    Messages:
    81
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #5
    No problem :). Array_slice is, as the name says, for slicing arrays and not replacing elements of an array.
     
    adstracker, Mar 13, 2006 IP