0

I was wondering how can I check if an array is empty or not in a function

Here is part of my code.

if (!mysqli_query($dbc, $sql)) {
        trigger_error(mysqli_error($dbc));
        return;
} else {
    $t = array();
    while($row = mysqli_fetch_array($result)) {
        $t[] = $row[0];
    }
}

if($tr > 0){
    $ts = array_sum($t);
}
8
  • $t[] = $row[0] is going to give the same value to every element in the $t array. You need to put a counter in there. Commented Dec 22, 2010 at 19:07
  • if (empty($array)) and it doesn't matter inside of function or not Commented Dec 22, 2010 at 19:07
  • @JMC Creative, exactly where? Commented Dec 22, 2010 at 19:08
  • @Col. Shrapnel, "not in a function" but "if an array is empty or not" Commented Dec 22, 2010 at 19:10
  • @tang, before the while statment you could put ` $i = 0 ` then inside the while loop, you would put ` $t[] = $row[$i]; $i++ ` Commented Dec 22, 2010 at 19:10

6 Answers 6

1

Use the empty() function: http://php.net/manual/en/function.empty.php

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

1 Comment

Not a function, but a language construct. Slightly different.
1

Loose equivalency checking returns false on an empty array

if(array()) // returns false

http://php.net/manual/en/types.comparisons.php

Comments

0

Use count() to count the number of elements in the array.

Comments

0

An easy method would be to use the count function.

For example:

if(count($sourceArray) != 0) {
    // Do exciting things here...
}

Comments

0
empty($t);

gives you true if $t is considered empty.

Comments

0

To check if array is empty:

if (sizeof($arr) == 0)
{
    //Empty array
}

To check whether an element exists in an array or not:

if (in_array($element, $arr))
{
     //Element found in the array
}

Comments

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.