Page 1 of 1

trouble with in_array

Posted: Mon Aug 03, 2009 5:27 pm
by jawaiah
I am searching an index array of my database's primary keys for some target keys.
I use the function in_array to check if my target pkeys exist, for each table in the DB.
This works fine when I only have one string as a needle, but when I try an array of strings as the needle for in_array I get no match (even if there's only one string in the array).

I was under the impression that you could pass an array needle.

If someone could please clarify how i am misusing in_array() i would greatly appreciate it.

Here's my debug output for a string needle:

Code: Select all

KOAPI pkeys: Array ( [0] => username
needle: username
 
MATCH FOUND
 
and here's what comes up with an array needle

Code: Select all

KOAPI pkeys: Array ( [0] => username 
needle: Array ( [0] => username
 
NO MATCH
 

Code: Select all

function dbFindField($fields)   //Finds table containing fields in db
    {
        foreach(array_keys($this->pkindex) as $table)  //Check each table's pkeys
            {
                echo "$table pkeys: "; print_r_tree($this->pkindex[$table]);
                echo "neelde: "; print_r_tree($fields);
                if(in_array($fields, $this->pkindex[$table])) echo "MATCH FOUND<p/>";
                else echo "NO MATCH<p/>";
                if(count($fields) == count($this->pkindex[$table])
                && in_array($fields, $this->pkindex[$table]))   //If same as field
                {
                    echo "success<p/>";
                    return $table;
                }
            }
            return FALSE;
    }

Re: trouble with in_array

Posted: Mon Aug 03, 2009 6:52 pm
by m4rw3r
You're searching wrong, because it would search for the array array('username') in the pkeys array which only contains the string 'username'.
This may work instead:

Code: Select all

 
if(count($fields) == count($this->pkindex[$table]) && count($fields) == count(array_intersect($fields, $this->pkindex[$table])))
{
    // ...
 
I don't think it is the most effective solution seen from a performance perspective, but it should work.

EDIT: Fixed a few grammar errors