Jonathan Lagenhorst Jonathan Lagenhorst - 4 years ago 112
PHP Question

How do i place elements in this php array 1 index further?

I have to make a little script for a school assignment which places the days of the week in chronological order with an index in front of them. Although Sunday has to be the first day and therefore must have the number 1 in front of it. (2 Monday, 3 Tuesday etc.)

I have tried to do this by placing all the elements in the array one index further but it does not seem to work.

$myArray = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
for ($i=0; $i<count($myArray); $i++) {
$myArray[$i] = $myArray[$i+1];
echo ($i+1) . " " . $myArray[$i] . "<br>";
}


And here is the error message i get when i execute the code:


1 Tuesday

2 Wednesday

3 Thursday

4 Friday

5 Saturday

6 Sunday



Notice: Undefined offset: 7 in C:\xampp\htdocs\opdracht_22.php on line 13

7


The result i am trying to get is:

1 Sunday

2 Monday

3 Tuesday

4 Wednesday

5 Thursday

6 Friday

7 Saturday


Is there anything i am missing here? How can i improve my code?

Answer Source

You can achieve the desired result using simple while loop,

<?php
    $myArray = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
    $array_length = count($myArray);  // $array_length is 7
    $index = $array_length - 1;  // $index is 6 here 
    $counter = 1;  // here $counter is used to print Nth weekday
    while(true){
        echo $counter . " " . $myArray[$index] . "<br />";
        $index = ($index + 1) % $array_length;  // performs increment and modulus operation to get the reminder value
        ++$counter;
        if($index == $array_length - 1){  // whenever $index is 6 again the loop will terminate
            break;
        }
    }
?>

Output:

1 Sunday
2 Monday
3 Tuesday
4 Wednesday
5 Thursday
6 Friday
7 Saturday
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download