PHP 8.4.24 Released!

Voting

: max(two, nine)?
(Example: nine)

The Note You're Voting On

raat1979 at gmail dot com
10 years ago
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();     //get all values
        $values[0]= &$array;        //REFERENCE!
        $org=key($array);              //where are we?
        call_user_func_array('array_push',$values);
        end($array);                 // move to the last item
        $key = key($array);         //get the key of the last item
        if($org===null){
            //was at eof, added something, move to it
            return $key;
        }elseif($org<(count($array)/2)){ //somewhere in the middle +/- is fine
            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

<< Back to user notes page

To Top