Current iterative position

Is there a way in PHP to move a specific iteration to a specific position in a loop?

For example, I have an array:

1, 2, 3, 4, 5, 6, 7, 8, 9

We have an array from 1 to 9, but I want 5 to be placed at the end of the iteration, so the result will look like this:

1
2
3
4
6
7
8
9
5
+4
source share
2 answers

It is not clear what you are asking. In any case, you can get the desired result using unsetand[] operator

$element = $array[4];
unset($array[4]);
$array[] = $element;

Live: http://codepad.org/cWZHjJwy

If you need to search for only 5, just enter the key with array_search():

$key = array_search(5,$array);
unset($array[$key]);
$array[] = 5;
+2
source

5, . , .

$numbers = range(1, 9);

// find the position of value 5
$position = array_search(5, $numbers);

// save the value and remove from array
$value = $numbers[$position];
unset($numbers[$position]);

// add it back at the end
$numbers[] = $value;

// print the values
foreach ($numbers as $number) {
    echo $number . ' ';
}

1 2 3 4 6 7 8 9 5

+1

All Articles