0

I have a php script that returns a JSON encoded array. It works correctly, but I need to check if it's empty. My problem lies in the fact that it's an array of arrays. How can I properly check for an empty array on the server side?

The PHP script (the important stuff)

$data = array();
foreach ($results = $db->getRows('SELECT * FROM users WHERE username !=?', [$username]) as $result) {
$name = $result['username'];
$lat = $result['lat'];
$lng = $result['lng'];
$distance = getDistance($user_lat, $user_lng, $lat, $lng);

if(withinRange($distance, $selected_distance, $selected_distance + 4)) {       
    //This is what's populated if data is available
    $data[] = array('name'=>$name, 'lat'=>$lat, 'lng'=>$lng); 
}

$response = array('data' => $data);
echo json_encode($response);

If data exists, it looks like this:

{"data":[{"name":"test_user2","lat":"35.932517","lng":"-89.905343"}]}

I have tried:

if(empty($response)
if(count($response) < 1)

but neither worked. Am I trying to access the wrong array? If so, how do I access the correct one to check for no data?

3
  • $response will never be empty, but $response['data'] or $data may be. Commented Sep 26, 2018 at 21:47
  • 1
    @FelippeDuarte Post that as an answer. Commented Sep 26, 2018 at 21:49
  • 1
    I figured it out, but if you wanna answer, I'll go ahead and give you the accept points. Commented Sep 26, 2018 at 21:50

2 Answers 2

1

$response will never be empty, but $response['data'] or $data may be

$response is an array with a key named "data", so the size will always be 1.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for pointing out that second part @Felippe. I should've known better.
0

you need to check $data, like so:

if(sizeof($data) === 0){echo "Empty";}

1 Comment

Yep. That's exactly what I was doing wrong. Accessing the wrong array. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.