note 49579 added to ref.array
| From: | daniel_doteherbert_atgmail_dotcom at osu1 dot php dot net | Date: | Wed, 02 Feb 2005 05:52:54 +0000 |
| Subject: | note 49579 added to ref.array | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-84356@lists.php.net to get a copy of this message | ||
i was unable to use normal means to shift an array element up or down, so i had to write a function
to do it... i havent had the chance to test it, but the method is there...
<?
$stuff[0] = 'a';
$stuff[1] = 'b';
$stuff[2] = 'c';
$stuff[3] = 'd';
function array_shift($array,$value,$direction = 'up')
{
$temp = $array;
/* search for the value */
while ($array_value = current($array))
{
if ($array_value == $value)
{
$key = key($array);
break;
}
next($array);
}
/* no key */
if ( !isset($key) )
{
return false;
}
/* check if we are at the top or bottom of the array and want to do an invalid move
ie: top element up, bottom element down
- return the original array... */
if ( $key == 0 && $direction == 'up' )
{
return $array;
}
if ( $key == (count($array)-1) && $direction == 'down' )
{
return $array;
}
/* reorder the elements */
switch ($direction)
{
case 'up':
$factor = -1;
break;
case 'down':
$factor = 1;
break;
}
$temp[$key+$factor] = $array[$key];
$temp[$key] = $array[$key+$factor];
/* return the ordered array */
return $temp;
}
?>
$stuff = array_shift($stuff,'c','up'); - will move c up and b down
$stuff = array_shift($stuff,'a','down'); - will move a down and b up
$stuff = array_shift($stuff,'a','up'); - will return the original array
$stuff = array_shift($stuff,'d','down'); - will return the original array
... if the element value could not be found it probably should return the original array instead of
false...
----
Manual Page -- http://www.php.net/manual/en/ref.array.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+49579
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+49579&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+49579&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+49579&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+49579&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+49579&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+49579&report=yes
Search -- http://master.php.net/manage/user-notes.php