Jump to content

drowning in comparison of 2 arrays


fife

Recommended Posts

I'm having trouble comparing two arrays. Ive never worked with arrays like this till today so bare with me. Ill explain as best I can with my code. So I have one array Im pulling from the database. which I get as follows

 


//now get all the tags
mysql_select_db($db, $db);
$getq = mysql_query("SELECT * FROM blogtags",$db);
//create the tags array
$arr1 = array();
do{
$arr1[] = $row['tagname'];
}while($row = mysql_fetch_assoc($getq));

 

If I print the outcome of this $arr1

 

array(3) { [0]=> NULL [1]=> string(4) "cars" [2]=> string(4) "vans" }

 

cars and vans are the only 2 entries in the database

 

Next I have a form field called $_POST['hidden-tags']; which stores data as ....... tanks, bikes, trains

 

here is the code I have to turn that into an array

 


$arr2[] = explode(",",$_POST['hidden-tags']);

 

if I echo that out I get

 

array(1) { [0]=> array(4) { [0]=> string(4) "cars" [1]=> string(5) "bikes" [2]=> string(6) "trains" [3]=> string(5) "tanks" } }

 

which are entries into the form (cars, bikes, trains, tanks)

 

Now Im trying to only show items that are not in the first array with array_diff but for some reason it doesnt work correctly. First I can see in the second array does not look like the first and I dont understand why but im sure thats coursing problems!!!!!

 

secondly If I run the code

 


//show only items in the second array that are not in the first
$tmp = array_diff($arr2, $arr1);
var_dump($tmp);

 

then this pops out

array(1) { [0]=> array(4) { [0]=> string(4) "cars" [1]=> string(5) "bikes" [2]=> string(6) "trains" [3]=> string(5) "tanks" } }

 

surely this should just show bikes, trains, tanks and not the cars as it appears in $arr1

Link to comment
https://forums.phpfreaks.com/topic/274070-drowning-in-comparison-of-2-arrays/
Share on other sites

You should NOT use a do . . . while() loop when processing your database results. That is why you get a NULL value at the beginning of the array.

do{
   $arr1[] = $row['tagname'];
}while($row = mysql_fetch_assoc($getq));

 

On the first iteration of that loop $row is not defined. Use a while() loop instead

while($row = mysql_fetch_assoc($getq))
{
   $arr1[] = $row['tagname'];
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.