Ando
Ando

Reputation: 1847

Comparing arrays with non-arrays with array_diff()

I'm getting some data from various db tables using CodeIgniter. Funny thing is that 10 lines above this code I was testing the concept with some other arrays which had names and everything worked as expected.

Now that I'm trying the same thing with the data from my db, it doesn't seem to be working.

Code

echo "a:"; print_r($CITB);
echo "<br />b:"; print_r($PRB);
echo "<br />c:"; print_r($TB);
echo "<br />d:"; print_r($TRB);


$a = $CITB; //I know this is empty
$b = array_diff($PRB,$a);
$c = array_diff($TB, $b, $a);
$d = array_diff($TRB, $c, $b, $a);

echo "<br /><br />a:"; print_r($a);
echo "<br />b:"; print_r($b);
echo "<br />c:"; print_r($c);
echo "<br />d:"; print_r($d);die();

Result

a:
b:Array ( [0] => 8 [1] => 52 ) 
c:Array ( [0] => 8 [1] => 52 ) 
d:

a:
b:
c:
d:

Expected result

a:Array()
b:Array ( [0] => 8 [1] => 52 ) 
c:Array()
d:Array()

Upvotes: -1

Views: 202

Answers (1)

air4x
air4x

Reputation: 5683

The arguments to array_diff should be arrays. Otherwise it will return null.

In your case print_r($CITB); doesn't print as Array() which means it is not an empty array and most likely an empty string. So $b = array_diff($PRB,$a); results in $b being null.

If you turn on error reporting you should see some warnings. Otherwise use var_dump instead of print_r to see the types for the variables.

Upvotes: 1

Related Questions