hello guys I need your help regarding to this array problem. I am struggling with this for hours already. I can't let it work. Here's the problem: I need an array that every time I put a value on it. it will auto delete a value at the front and move it at the very last part of the added value of an array. For example: This is my code: $arr = array(1,2,3,2,4); $lvl = 2; foreach($arr as $tmp) { if($tmp > $lvl) { $tmp-=1; } echo $tmp."<br />"; } PHP:
If I understood you correctly you want this: function add_value($arr,$new_value){ if(empty($arr)){ return false; } $first_value = $arr[0]; foreach($arr as $key => $value){ if($key!=0){ $new_arr[$key-1] = $arr[$key]; } } $new_arr[] = $new_value; $new_arr[] = $first_value; return $new_arr; } $arr = array(1,2,3,4,5); $arr = add_value($arr,6); foreach($arr as $tmp) { echo $tmp." "; } PHP: To add a new value use add_value() function.
^ The problem with that though is if you add another value, it'll output this: I have similar code and similar problem: <?php $arr = array(1,2,3,2,4,5); $arr = add(6); foreach ($arr as $lol) { echo "$lol "; } function add($lol) { global $arr; array_push($arr, $lol); $temp = $arr[0]; array_shift($arr); $arr[] = $temp; return $arr; } ?> PHP: But it runs according to OP's instruction so I didn't bother changing it..
$arr = add_value($arr,6); $arr = add_value($arr,7); $arr = add_value($arr,8); etc. PHP: But OP's instruction is right on, it just doesn't look right.
Rainulf, I want that you say me which one will look right. After adding those values how it has to show the numbers?
hello guys! thanks for your reply and help. Yes Rain is right after adding couple of value the sequence output doesn't seems to be right. I really appreciate your help guys for more example default value are array(1,2,3,4,5) and after adding 6 and 7 the output should be look like this 3 4 5 6 7 1 2 but the code is out putting this 3 4 5 6 1 7 2
So do it like this: function add_values($arr,$values){ $values = explode(",",$values); foreach($values as $value){ $arr[] = $value; } for($i=0; $i<count($values); $i++){ $tmp_value = $arr[0]; array_shift($arr); $arr[] = $tmp_value; } return $arr; } $arr = array(1,2,3,4,5); $arr = add_values($arr,"6,7,8"); foreach($arr as $tmp) { echo $tmp." "; } PHP: