williamZanelli Posted November 25, 2008 Share Posted November 25, 2008 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.. Quote Link to comment https://forums.phpfreaks.com/topic/134140-for-loop-help/ Share on other sites More sharing options...
premiso Posted November 25, 2008 Share Posted November 25, 2008 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. Quote Link to comment https://forums.phpfreaks.com/topic/134140-for-loop-help/#findComment-698272 Share on other sites More sharing options...
williamZanelli Posted November 25, 2008 Author Share Posted November 25, 2008 Thanks for the reply. The problem was due to the missing '$' sign. Very embarassing. Thanks for your help. Have a great week Quote Link to comment https://forums.phpfreaks.com/topic/134140-for-loop-help/#findComment-698292 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.