Page 1 of 1
function already available?
Posted: Wed Jul 12, 2006 7:51 pm
by s.dot
Is there a PHP function to push a numerical keyed array up by one?
IE
becomes
Maintain the values in the same order, just bump each key up by a number.
?
Posted: Wed Jul 12, 2006 7:53 pm
by MarK (CZ)
I don't think there's a function for that, but one nice loop would do the trick, wouldn't it?

Posted: Wed Jul 12, 2006 8:01 pm
by Christopher
Posted: Wed Jul 12, 2006 8:03 pm
by s.dot
I was thinking a loop or array_walk(), just felt kinda "dirty" =/
but thanks

Posted: Wed Jul 12, 2006 8:20 pm
by Ambush Commander
Two functions will do the trick:
Code: Select all
$array = array(0 => 'foo', 1 => 'bar'); // numerical array you want to shift
array_unshift($array, null);
unset($array[0]);
var_dump($array);
Posted: Wed Jul 12, 2006 8:23 pm
by Benjamin
This work?
Code: Select all
<?php
$ThisArray = array('0' => 'Zero','1' => 'One','2' => 'Two','3' => 'Three');
$NewArray = array();
reset($ThisArray);
while (list($Key, $Value) = each($ThisArray)) {
$Key = $Key + 1;
$NewArray[$Key] = $Value;
}
print_r($NewArray);
?>
Edit: You beat me

Posted: Wed Jul 12, 2006 8:24 pm
by Ambush Commander
I think my way is better.

Posted: Wed Jul 12, 2006 8:25 pm
by Benjamin
Yeah you beat me and it's better.
Posted: Wed Jul 12, 2006 8:29 pm
by dull1554
i love when you blink and like four other people answer the question.

Posted: Wed Jul 12, 2006 8:29 pm
by s.dot
perfect, thanks