Search code examples
phpstrpos

strpos not working with $post method


I have a IF Statement where when i submit my page it is going to check if the time exists already and if so assign a value to my variable or echo out a message saying it found the time. Doesnt seem to be working though, i tried == true and !== false but no luck.

Below is code thanks.

$alarm = $_POST[add];
$alarms = explode("\n", shell_exec("crontab -l")); //grab schdules
array_pop($alarms); //remove empty last line

foreach($alarms as $alarm)
{
    if (strpos($alarm, $alarm['alarmhour']) !== false)
    {
        $HourSuccess = "Correct";
        $message121 = "We found the same time.. ";
        echo "<script type='text/javascript'>alert('$message121');</script>";
    }
}

$alarm['alarmhour'] is my post method which will have a value of 1-23. $alarm is looping through my schedules and i have one in there lets say for 2 o clock. If i type two and try run, it doesnt find it?

P.s: When i echo out my $alarm['alarmhour'] it returns the value i entered correctly.


Solution

  • You defined $alarm twice.

    The first line defines $alarm as the value of a value from $_POST, which is OK.

    The foreach line iterates $alarms with each value being stored to $alarm, which is also correct. But it will overwrite the original value.

    Look at this line:

    if(strpos($alarm, $alarm['alarmhour']) !== false)
    

    Don't you think there is a problem using the same variable differently?

    Instead, you should probably give a new name to the variable defined on line 1 (e.g. $postedAlarm), and refactor correct usages in lines below.