Jump to content

For Loop help


williamZanelli

Recommended Posts

Hey guys, I have a problem, Its trivial, but I cant see where I'm going wrong

 

Ok, so I extract some data from my database, explode it and create and array

 

$user_media = explode(", ", $user_media_string->mediatype);
print_r ($user_media); 

 

The above prints

 

Array ( [0] => Item1 [1] => Item2 )

 

Then  I have the followng loop (I'm trying to create a WHERE staement for some SQL later)

 

if((count($user_media) + 1)  >1 )
{

$where_sub =" _name = '".  $user_media[0] . "'";

for($i=1;$i<count($user_media);$i++)
{

		$where_sub .= " or _name= '". $user_media[i] . "'";

}	

}
else
{

$where_sub ="_name = '". $user_media[0]  . "'";

}

 

The $user_media [0] returns the correct value, howveer in the loop, when the value  $user_media[1] is being accessed, it comes out as blank,

 

What am I doing wrong? This is driving me craqzy

 

??? ???

 

Thank in advance for your help/pointers..

 

Link to comment
https://forums.phpfreaks.com/topic/134140-for-loop-help/
Share on other sites

Arrays are zero index based. So 0 is the starting. Count returns the actual number which can cause problems. This should fix the error.

 

if (count($user_media)   >1 ) {
   $where_sub =" _name = '".  $user_media[0] . "'";
   
   for($i=1;$i<count($user_media);$i++) {         
         $where_sub .= " or _name= '". $user_media[($i-1)] . "'";            
   }
}else { 
   $where_sub ="_name = '". $user_media[0]  . "'";
}

 

OR

 

if (count($user_media) > 1 ) {
   $where_sub =" _name = '".  $user_media[0] . "'";
   $cnt = count($user_media) - 1;
   for($i=0;$i<$cnt;$i++) {         
         $where_sub .= " or _name= '". $user_media[$i] . "'";            
   }
}else { 
   $where_sub ="_name = '". $user_media[0]  . "'";
}

 

And you were also calling i instead of $i.

 

Hope that helps.

Link to comment
https://forums.phpfreaks.com/topic/134140-for-loop-help/#findComment-698272
Share on other sites

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.