简体   繁体   中英

PHP in_array results always same.

<?php
    $a = $monitoring->getMonitoringServers();
    if (in_array("192.168.100.253", $a))
        echo "y";
    else
        echo "n";
?>

print_r($a) yields:

Array (
   [0] => stdClass Object ( [address] => 192.168.100.253 )
   [1] => stdClass Object ( [address] => 192.168.100.253 )
) 

What's wrong with this code? The answer is always no!

Your array is made of objects, not strings.

By doing in_array("192.168.100.253", $a) you are looking for the string "192.168.100.253" inside $a, and as you can see on the print_r - it's inside an object.

$flag = false;
foreach($a as $obj){
  if($obj->address == "192.168.100.253"){
     $flag = true;
     break;
  }
}

if($flag){
   echo 'Y';
}
else{
   echo 'N';
}

$a is array of stdObjects, and you are treating them as normal values.

You are required to use a foreach loop to iterate through each element of $a.

The $a var is an object, not an array.

See http://www.php.net/manual/en/function.in-array.php#103983 for a function that also works on objects.

its simple try dis

$a = $monitoring->getMonitoringServers();

if (.in_array("192.168.100,253"; $a->address ) echo "y"; else echo "n"? ?> ul get output as n

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM