0

I am a little rusty in PHP after several years without programming with this language.

I am fetching data from an array in mySQL using PHP.

My problem is that at some point I fetch data from a table, using this:

$myArray = mysql_fetch_array( $data ); 

but at some point, the data base may be empty, so $myArray will be null or contain no elements.

Then I have to check if a particular string that is generated on-the-fly is on $myArray. If it is, another string must be generated and verified if it already exists on $myArray.

$myString = generateString();
if (in_array($myString, $myArray)) {
    $myString = generateString();
}

this code gives me this error:

Warning: in_array() [function.in-array]: Wrong datatype for second argument

To prevent in_array from running when $myArray is empty I did this:

if (count($myArray) > 0) {
    if (in_array($myString, $myArray)) {
        $myString = generateString();
    }
}

but count is giving me 1 when the array is empty (?)...

How do I solve that?

just another question: $myString is being modified inside the IF that is already testing it. Is this possible in PHP?

2
  • The mysql-extension is outdated and the use is discouraged. Use MySQLi or PDO_MYSQL instead. php.net/manual/en/function.mysql-connect.php Commented Nov 18, 2012 at 22:00
  • According to documentation, you are probably getting false back. Can you post the output of var_dump($myArray)? On a side note, mysql_* are soon to be deprecated, take a look at PDO or mysqli instead. Commented Nov 18, 2012 at 22:00

1 Answer 1

2

Well, if your query failed, you'll have... wait for it... no array!

So that in_array call would give you a warning about $myArray not being an array (but false).

You need to check your query for errors, and better yet:

Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

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

2 Comments

Where did you take this box from? Beside that a referece is always good: I want it :D
stackapps.com/q/2116. Comment source code can be found here: gist.github.com/3881905

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.