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
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
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.
No problem . Array_slice is, as the name says, for slicing arrays and not replacing elements of an array.