PHP array intersect question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
if0xy0
Forum Newbie
Posts: 2
Joined: Wed Mar 30, 2011 12:15 pm

PHP array intersect question

Post 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);  								
?>
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: PHP array intersect question

Post 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.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
if0xy0
Forum Newbie
Posts: 2
Joined: Wed Mar 30, 2011 12:15 pm

Re: PHP array intersect question

Post 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
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: PHP array intersect question

Post 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.
Post Reply