Sokhrat Sikar
Sokhrat Sikar

Reputation: 175

Checking if the array in foreach loop is empty or not

I am trying to check if my array is empty or not but strangely I can't get it working.

foreach ($friend as $key => $id){

    $friendActivity = $db->friendActivity($id);

    if (!empty($friendActivity)) {

        //rest of the code

    }

}

I have used var_dump($friendActivity) before the if statement and the result is as follow:

array(0) { } array(0) { } array(0) { } array(0) { } array(0) { } array(0) { }  

//////---> Something to know <--------/////////

I am not trying to see the count of arrays. Each user in database has some activities. I want to see if those activities match with the (poll of of activities). So if the user has mentioned about their activities, therefore the $friendActivity is not going to be empty.

If I use empty:

if (empty($friendActivity)){

    //rest of the code

}

I am able to get inside the if condition...

I personally think, that I have to delete the array at the end of each foreach loop, so that I don't store the other user's friends activities.

Upvotes: 1

Views: 11993

Answers (2)

Paweł
Paweł

Reputation: 1

You can try this solution:

if (sizeof($friendActivity) > 0) {

Upvotes: 0

Jonathan LeBlanc
Jonathan LeBlanc

Reputation: 788

count() should give you an accurate array number: http://php.net/manual/en/function.count.php

if (count($friendActivity) > 0) {
   ...
}

Upvotes: 3

Related Questions