1

I am trying to check whether an entry exists (one or more) in our database. However, even when I know there are no entries, I am getting an array which has a first entry of zero. Therefore it is not empty and I am not getting what I need.

Here's my code:

    <?php
    $query = mysql_query("SELECT * FROM table WHERE column = $yfbid_number AND timestamp BETWEEN (NOW()- Interval 1 DAY) AND NOW()");
    $array[] = array();
    while ($row = mysql_fetch_assoc($query)){
        $array[] = $row['column'];
    }
    ?>

When doing print_r on an array which should be empty, I am getting: ( [0] => Array ( ) ) and therefore count is 1 and not zero, which messes up my code. Any ideas how to get to a truly empty array in this situation? I'd rather not delete this entry but avoid it in the first place, because in most use cases I will get either an empty array or one that only has one entry (a real entry), in which case I will want to easily distinguish between the two. (as it is now, both give a count of 1 entry, which is very bad for our porpuses). Thanks.

3 Answers 3

4

Change:

$array[] = array();

to

$array = array();

With your version, if $array doesn't already exist, PHP will first create an array, then append an empty array to it. So you end up with a 1 element array whose only member is an empty array.

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

Comments

3

$array[] = array(); should be $array = array(). Right now, you are appending an array element to an array that is initialized. Turn notices on and you'll get a complaint about an undefined variable (probably).

Comments

1

I suggest you first do a SELECT COUNT(*) to determine how many entries you'll get. Then you KNOW that the result will be a useful answer, and can make or not make a subsequent query on the basis of your result.

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.