note 105907 added to ref.array

From: Date: Sat, 24 Sep 2011 18:57:00 +0000
Subject: note 105907 added to ref.array
Groups: php.notes 
Request: Send a blank email to php-notes+get-183407@lists.php.net to get a copy of this message
While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys. The following array_rotate() function uses array_merge and array_shift to reliably rotate an array forwards or backwards, preserving keys. If you know you can trust your $array to be an array and $shift to be between 0 and the length of your array, you can skip the function definition and use just the return expression in your code. <?php function array_rotate($array, $shift) { if(!is_array($array) || !is_numeric($shift)) { if(!is_array($array)) error_log(__FUNCTION__.' expects first argument to be array; '.gettype($array).' received.'); if(!is_numeric($shift)) error_log(__FUNCTION__.' expects second argument to be numeric; '.gettype($shift)." $shift received."); return $array; } $shift %= count($array); //we won't try to shift more than one array length if($shift < 0) $shift += count($array);//handle negative shifts as positive return array_merge(array_slice($array, $shift, NULL, true), array_slice($array, 0, $shift, true)); } ?> A few simple tests: <?php $array=array("foo"=>1,"bar"=>2,"baz"=>3,4,5); print_r(array_rotate($array, 2)); print_r(array_rotate($array, -2)); print_r(array_rotate($array, count($array))); print_r(array_rotate($array, "4")); print_r(array_rotate($array, -9)); ?> ---- Server IP: 192.41.42.26 Probable Submitter: 68.226.95.193 ---- Manual Page -- http://www.php.net/manual/en/ref.array.php Edit -- https://master.php.net/note/edit/105907 Del: integrated -- https://master.php.net/note/delete/105907/integrated Del: useless -- https://master.php.net/note/delete/105907/useless Del: bad code -- https://master.php.net/note/delete/105907/bad+code Del: spam -- https://master.php.net/note/delete/105907/spam Del: non-english -- https://master.php.net/note/delete/105907/non-english Del: in docs -- https://master.php.net/note/delete/105907/in+docs Del: other reasons-- https://master.php.net/note/delete/105907 Reject -- https://master.php.net/note/reject/105907 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#183407) next »