views:

56

answers:

1

Hi Everyone,

I'm having a tough time with this one, I have a class which populates an array.

Sometimes the array will not be populated and I want make an edge-case for when this happens however I can't seem to tell when its null! Here's the code:

$results_dev = $class->get_data_nologin("4a9d-4f41-9566-7705",$key,"Sensors");
    echo "something";
    print_r($results_dev);

    if(is_null($results_dev))
    {   
        echo "thisisNULL";
        $counter--;
    }

"something" does get echoed out, but when I print_r $results_dev, it prints "null" and the if statement never executes! I've also tried

if(!$results_dev)

and

if($results_dev == "null")

and

if($results_dev == null)

But it still doesn't execute whats in the if loop, how else could I check this?

BTW: my class curls an API and retrieves a JSON, however sometimes the URL is incorrect in curl so it returns null. What's even worse is after this I have:

if($results_dev['location'])
    {
        echo "data".$results_dev['location'];

And It executes even when its null! It prints "data" and absolutely nothing afterwards.

code for get_data_nologin:

    $url = 'https://api.url/'.$scf.'/'.$deviceid.'?key='.$apikey;
    $curl_handle = curl_init();
    curl_setopt($curl_handle, CURLOPT_URL, $url);
    curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE); 
    curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
    curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl_handle, CURLOPT_COOKIEJAR, $cookie_file_path);
    curl_setopt($curl_handle, CURLOPT_COOKIEFILE, $cookie_file_path);
    $buffer = curl_exec($curl_handle);
    curl_close($curl_handle);
    if (empty($buffer)) 
    {
        echo 'Something went wrong :(';
    } 
    else 
    {

            $decodedBuffer = json_decode($buffer, TRUE);

            return $decodedBuffer;

    }

Any advice would help!

+3  A: 

use isset($results_dev)

if(!isset($results_dev)){
 echo "thisisNULL";
        $counter--;

}

With new inputs this can be the solution:

if(strtolower($results_dev) == 'null'){ 
     echo "thisisNULL";
            $counter--;

}
Stewie
Thank you for responding, isset($results_dev) isn't triggering anything either
Pete Herbert Penito
See my edit above and use it like that.. see if it works
Stewie
If `$class->get_data_nologin` in OP's code returns an actual `NULL` value, `is_null` should work just as well as `isset`...
Daniel Vandersluis
@Daniel : Correct !! @Pete: stupid question, but.. does it return null as a string ? try this gettype($results_dev) and see what you get
Stewie
Good point Stewie! I did gettype and it appears to be a string..
Pete Herbert Penito
OK .. then do this: if(strtolower(gettype($results_dev)) == 'null'){
Stewie
Its not triggering anything, wouldn't that look like if(string == 'null')?
Pete Herbert Penito
OOPS .. if(strtolower($results_dev){} (My bad !)
Stewie
Thank you sir, you have led me in the right direction, :)
Pete Herbert Penito