I have a question about an if statement in the foreach loop.
<?php $time_code = 2; $times = array( '2' => '10:00', '4' => '12:00', '6' => '14:00', ); foreach($times as $code => $time){ //if $code >= time_code && $time_code < the next array_key } ?>
What I mean is if $time_code = 2 echo 10:00 but if $time_code is 4 or 5 echo 12:00.
Advertisement
Answer
Assuming that you want to check if the key is equal or equal + one, you could check conditional that sees if the variable is equal or equal + one. So it would look similar to the following…
Say we had a selector that allowed us to select a 24 hour time in increments of one hour and you want to get a code for that time. So if we have an array with those values set in increments of two, we write the conditional to see if the key is equal to or equal + one.
Now we have a html form like so:
<form action="" method="post"> <div>Choose a time <select name="time_code" id="time_code"> <option value="2">2:00</option> <option value="3">3:00</option> <option value="4">4:00</option> <option value="5">5:00</option> <option value="6">6:00</option> <option value="7">7:00</option> <option value="8">8:00</option> <option value="9">9:00</option> <option value="10">10:00</option> <option value="11">11:00</option> <option value="12">12:00</option> <option value="13">13:00</option> <option value="14">14:00</option> <option value="15">15:00</option> <option value="16">16:00</option> <option value="17">17:00</option> <option value="18">18:00</option> <option value="19">19:00</option> <option value="20">20:00</option> <option value="21">21:00</option> <option value="22">22:00</option> <option value="23">23:00</option> <option value="24">24:00</option> </select> </div> <input type="submit" name="submit" value="submit"> </form>
We get the post value and then compare the entry to our array using an if statement like so:
$output = null; // convert to integer for strict comparison or use == in conditional $time_code = (int)$_POST['time_code']; $times = array( '0' => '2:00', '2' => '4:00', '4' => '6:00', '6' => '8:00', '8' => '10:00', '10' => '12:00', '12' => '14:00', '14' => '16:00', '16' => '18:00', '18' => '20:00', '20' => '22:00', '22' => '24:00' ); $msg = null; foreach($times as $code => $time){ if($time_code === $code || $time_code === $code + 1){ $msg = $time; }else{ $msg = "error"; } } if($msg === 'error'){ $msg = "Sorry there is no time slot for that code, please check your entry!"; }
HTML:
<div> <?=$msg?> </div>
OUTPUT:
5:00 selected will output -> CODE: 4 2:00 selected will output -> CODE: 2 17:00 selected will output -> CODE: 16 23:00 selected will output -> CODE: 22 24:00 selected will output -> CODE: 24
*Because we have control over the select in terms of input for value, the error will never trigger… If you use a text input or something that allows the user to input values that are not within our parameter, then the error could trigger.