Unfortunately array_push returns the new number of items in the array
It does not give you the key of the item you just added, in numeric arrays you could do -1, you do however need to be sure that no associative key exists as that would break the assumption
It would have been better if array_push would have returned the key of the item just added like the below function
(perhaps a native variant would be a good idea...)
<?php
if(!function_exists('array_add')){
function array_add(array &$array,$value ){
$values = func_get_args(); $values[0]= &$array; $org=key($array); call_user_func_array('array_push',$values);
end($array); $key = key($array); if($org===null){
return $key;
}elseif($org<(count($array)/2)){ reset($array);
while (key($array) !== $org) next($List);
}else{
while (key($array) !== $org) prev($List);
}
return $key;
}
}
echo "<pre>\n";
$pr = array('foo'=>'bar','bar'=>'foo');
echo "Taken array;";
print_r($pr);
echo "\npush 1 returns ".array_push($pr,1)."\n";
echo "------------------------------------\n";
$pr = array('foo'=>'bar','bar'=>'foo');
echo "\npush 2 returns ".array_push($pr,1,2)."\n";
echo "------------------------------------\n";
$pr = array('foo'=>'bar','bar'=>'foo');
echo "\n add 1 returns ".array_add($pr,2)."\n\n";
echo "------------------------------------\n";
$pr = array('foo'=>'bar','bar'=>'foo');
echo "\n add 2 returns ".array_add($pr,1,2)."\n\n";
echo "<pre/>\n\n";
?>
Outputs:
Taken array;Array
(
[foo] => bar
[bar] => foo
)
push 1 returns 3
------------------------------------
push 2 returns 4
------------------------------------
add 1 returns 0
------------------------------------
add 2 returns 1