note 119229 added to function.array-push

From: Date: Sat, 23 Apr 2016 02:39:47 +0000
Subject: note 119229 added to function.array-push
Groups: php.notes 
Request: Send a blank email to php-notes+get-205305@lists.php.net to get a copy of this message
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 ---- Server IP: 72.52.91.14 Probable Submitter: 84.82.58.46 ---- Manual Page -- http://php.net/manual/en/function.array-push.php Edit -- https://master.php.net/note/edit/119229 Del: integrated -- https://master.php.net/note/delete/119229/integrated Del: useless -- https://master.php.net/note/delete/119229/useless Del: bad code -- https://master.php.net/note/delete/119229/bad+code Del: spam -- https://master.php.net/note/delete/119229/spam Del: non-english -- https://master.php.net/note/delete/119229/non-english Del: in docs -- https://master.php.net/note/delete/119229/in+docs Del: other reasons-- https://master.php.net/note/delete/119229 Reject -- https://master.php.net/note/reject/119229 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#205305) next »