Page 1 of 1

PHP array intersect question

Posted: Wed Mar 30, 2011 1:18 pm
by if0xy0
I've two arrays, one which consist of constant values, the other which get filled dynamically. I am trying to find out if the dynamically filled array include any of the values inside the constant array, and which value is it exactly, so I've used the following code which is for some reason don't work as expected, as it returns null in some cases :(

So can someone please help me and tell me what exactly I am doing wrong? Also is there a 'better' way to do it?

Thanks in advance for your time and efforts

NOTE: get_the_category and $category->cat_ID are two wordpress functions, which return the current category id and add it to the dynamic array

Code: Select all

<?php 
   unset($x);
   unset($arr);
   $x=array(4,3,7,1,31,43,38,63);   
  foreach((get_the_category()) as $category) { 
         $arr[] = $category->cat_ID ; 
  }

  $result = array_intersect($x, $arr);
  print_r($result);  								
?>

Re: PHP array intersect question

Posted: Wed Mar 30, 2011 2:07 pm
by AbraCadaver
If nothing in $arr is contained in $x, then $result will be an empty array. Other than that you would have to show some values for $arr and the print_r() of the result.

Re: PHP array intersect question

Posted: Thu Mar 31, 2011 3:52 pm
by if0xy0
Thanks a lot AbraCadaver for your time and effort. I already know this information, yet my problem is that sometime the code I posted work, sometime not so I was wondering if there is anything I am doing wrong in the php part

Thanks for taking the time to read my message

Re: PHP array intersect question

Posted: Thu Mar 31, 2011 5:18 pm
by McInfo
$arr is not properly initialized. So, if there are no categories, two errors will be triggered:
Notice: Undefined variable: $arr in ... on line ...
Warning: array_intersect(): Argument #1 is not an array in ... on line ...
Before the loop, assign an empty array to $arr.

Code: Select all

$arr = array ();
There is no benefit to unsetting the two variables because they are being set immediately after.

Invent more descriptive names for your variables. "x" and "arr" are not self-documenting.