0

For some reason this code won't run in my compiler. The intention (as part of a larger project) is to ping a particular host 3 times, or until successful, whichever comes first. It's not producing any errors, just terminating. It works just fine if I remove the second condition from the while statement, but then I would need to have something more complicated to terminate the loop on a successful ping. I haven't touched PHP in a while, so I'm probably missing something stupid.

<?php
function pingAddress($ip) {
//Set variable to limit loops and end if live
$pass = 0;
$result = 0;
//Create conditions for while loop
while( ( $pass < 3 ) && ( $result = 0 ) ) {
    //Count loops
    $pass++;
    //Execute ping
    $output=shell_exec('ping -n 1 '.$ip);
    //Display ping results for testing purposes
    echo "<pre>$output</pre>";
    //Check for "TTL" presence
    if(strpos($output, 'TTL') !== false)
    {
        //Notate positive result
        $result++;
        //Display for testing
        echo "Alive";
    }
    //Display negative result for testing
    else
    {
        echo "Dead";
    }
}
}


PingAddress("8.8.8.8");
Alex
  • 13
  • 1
  • 2

4 Answers4

6

You'll kick yourself:

while( ( $pass < 3 ) && ( $result = 0 ) ) {

Should use a double equals - it's a comparison, not an assignment:

while( ( $pass < 3 ) && ( $result == 0 ) ) {
RichardAtHome
  • 4,293
  • 4
  • 20
  • 29
4

You don't need the second variable $result. Use break instead.

while($pass < 3) {
    //Count loops
    $pass++;
    //Execute ping
    $output=shell_exec('ping -n 1 '.$ip);
    //Display ping results for testing purposes
    echo "<pre>$output</pre>";
    //Check for "TTL" presence
    if(strpos($output, 'TTL') !== false)
    {
        //Display for testing
        echo "Alive";

        break; //exiting while loop
    }
    //Display negative result for testing
    else
    {
        echo "Dead";
    }
}

You can even write less code with

while($pass++ < 3) {
Felippe Duarte
  • 14,901
  • 2
  • 25
  • 29
0

Your second condition is written incorrectly. Change it to $result === 0

Jon Wyatt
  • 79
  • 6
0

Use equal operator not assign.

while( ( $pass < 3 ) && ( $result == 0 ) )

This should work.