?
Solved

php in_array - unexpected behavior

Posted on 2010-03-30
7
Medium Priority
?
243 Views
Last Modified: 2013-12-13
Not sure why this is happening, but my script doesn't seem to be able to return true for in_array more than once...

I'm posting the code below:


$saved = '15,22';    
$set = explode(",",$saved); //results in Array ( [0] => 15 [1] => 22 ) 

//Then, I query the database:

$result = pg_query("SELECT did,vid,iid,value FROM demographicValues");
if(pg_num_rows($result) > 0) {
  while($r = pg_fetch_array($result)) {
     $demo[$r['did']][$r['vid']]['value'] = $r['value'];
     if(in_array($r['vid'], $set)) {
       $demo[$r['did']][$r['vid']]['status'] = 1;
     }
  }
} else...

/*
If I print_r $demo, you can see that the vid 22 is in there, so, I'm not understanding why the status isn't being set accordingly?
*/
    Array
    (
        [Mant] => Array
            (
                [15] => Array
                    (
                        [value] => Proper
                        [checked] => 1
                    )

                [16] => Array
                    (
                        [value] => Parish
                    )
        [Comp] => Array
            (
                [22] => Array
                    (
                        [value] => 65 - 70
                    )

                [23] => Array
                    (
                        [value] => 35 - 50
                    )
        )

)

Open in new window

0
Comment
Question by:n00b0101
7 Comments
 
LVL 34

Accepted Solution

by:
Beverley Portlock earned 2000 total points
ID: 29090968
Your array as shown in print_r layout does not have a key for "vid", just for "Mant" and "Comp" so it looks to me like in_array is correct
0
 
LVL 12

Expert Comment

by:Avinash Zala
ID: 29091151
Yes, bportlock that's what i am thinking since long..

Thanks
Addy
0
 
LVL 17

Expert Comment

by:Shinesh Premrajan
ID: 29091352
Actually there are two problems

The array that you are finally getting is due to the

 $demo[$r['did']][$r['vid']]['value'] = $r['value'];
If its entering the in_array condition then you should get the status also in the array, which is not there in the one you outputted.
 $demo[$r['did']][$r['vid']]['status'] = 1;

ok so try this

 if(array_search($r['vid'], $set))

instead if in_array()

Hope this helps
0
2018 Annual Membership Survey

Here at Experts Exchange, we strive to give members the best experience. Help us improve the site by taking this survey today! (Bonus: Be entered to win a great tech prize for participating!)

 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 29091599
@Addy... I was scratching my head my self.

@N00b0101 - are you expecting in_array to check the sub-arrays as well? In general PHP array functions only check the top leve of the array that you give them. If you want them to inspect sub-arrays then you need to consider looking at the array_walk function that applies a function to every member and sub-member of an array

http://uk.php.net/manual/en/function.array-walk-recursive.php
0
 
LVL 82

Expert Comment

by:hielo
ID: 29096893
You can try adding false as the third parameter:
if( in_array($r['vid'], $set,false) )

BUT if $set is large, the in_array may turn out to be slow. My suggestion would be to flip the $set array, so that the values become keys and then simply use isset():
$saved = '15,22';    
$set = array_flip(explode(",",$saved)); //results in Array ( [15] => 0 [22] =>1 ) 

//Then, I query the database:

$result = pg_query("SELECT did,vid,iid,value FROM demographicValues");
if(pg_num_rows($result) > 0) {
  while($r = pg_fetch_array($result,NULL,PGSQL_ASSOC)) {
     $demo[$r['did']][$r['vid']]['value'] = $r['value'];
     if( isset($set[ $r['vid'] ]) ) {
       $demo[$r['did']][$r['vid']]['status'] = 1;
     }
  }
} else...

Open in new window

0
 

Author Closing Comment

by:n00b0101
ID: 31708879
I'll accept this one as a solution, because my array was indeed, incorrect...  

When I did a var_dump instead of print_r, I saw that in my $set array, there was an extra space around the value.  So, I fixed that and was able to get it to work... Really appreciate everyone's input...  
0
 
LVL 82

Expert Comment

by:hielo
ID: 29115768
Well this is a surprising "solution".
>>Your array as shown in print_r layout does not have a key for "vid", just for "Mant" and "Comp" so it looks to me like in_array is correct

The commented code clearly states:
If I print_r $demo

but the statement is:
if(in_array($r['vid'], $set))

Notice that it is searching in $set, NOT in $demo! So of course it will not find it.

However, from the posted result of print_r, $['vid'] seems to be 22, which does exist in $set!!
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this. Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it i…
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

594 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question