1

I'm looking for an answer on something I've been literally spending my whole weekend on, and been struggling to find the right way to do it.

Say I have this PHP array:

Array (
    [0] => 0
    [1] => 182
    [2] => 185
    [3] => 0
    [4] => 187
    [5] => 0
    [6] => 0
)

The key for each row of this array is a day, based on the numeric representation of the day of the week (1 = Monday, 2 = Tuesday, etc.).

I want to get the value for today's day, but if it's empty, I want to get the next non-zero value. It also needs to reset back to Sunday (0) if Saturday (6) equals 0.

Please help :S

1 Answer 1

1
<?php
$day = date('w'); // Getting today day number
$myArray = [0, 182, 185, 0, 187, 0, 0]; // Your array



function getValue($day, $myArray){

    $loopCount = 0; // avoid infinite loop

    for($i = $day; $i <= 7; $i++){

        // $i == 7 <=> $i = 0
        if($i == 7){
            $i = 0;
        }

        // Check if the value can be returned
        if($myArray[$i] != 0){
            return $myArray[$i];
        }


        $loopCount++;

        // If we have checked the whole array, we return null
        if($loopCount == 7){
            return null;
        }
    }
}

echo getValue($day, $myArray);
?>

Can you test this code and tell me if it's what you are looking for?

This code should be really easy to understand, but don't hesitate to ask me if you need some explanations.

Sign up to request clarification or add additional context in comments.

1 Comment

Bingo! Thank you so much Vico! Your help is greatly appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.