Php Rotate And Adding To An Array
Is it possible to do something like the following in PHO I return an array from my DB that looks like the following 1, 2 ,3 now i want to add a forth number to it and then resort t
Solution 1:
You can use the below function and pass the shifting parameter to it. The function name is rotate_array() below. After using the function add the next value.
<?php$weekdays = array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");
functionrotate_array($steps, $arr)
{
if($steps >= 0)
{
for($i = 0; $i < $steps; $i++)
{
$elm = array_shift($arr);
array_push($arr, $elm);
}
}
else
{
for($i = 0; $i > $steps; $i--)
{
$elm = array_pop($arr);
array_unshift($arr, $elm);
}
}
return$arr;
}
$arr = rotate_array(1, $weekdays);
//For multidimensional array, add this partforeach($arras$key => $childArray) {
rotate_array(1,$childArray);
}
//end of addition$arr[] = "next value";
echo"<pre>";
print_r($arr);
echo"</pre>";
?>Output:
Array
(
[0] => Tue
[1] => Wed
[2] => Thu
[3] => Fri
[4] => Sat
[5] => Sun
[6] => Mon
[7] => next value
)
Post a Comment for "Php Rotate And Adding To An Array"