----- Original Message ----- From: "Petre Agenbag" <[EMAIL PROTECTED]> To: <[EMAIL PROTECTED]> Sent: Monday, July 14, 2003 4:11 AM Subject: [PHP] elegant way of doing something else the last time through a loop?
> HI list > > Is there an elegant way to know when the last time through the loop is > going to be and to do something else? > > > I want to search through a table by "exploding" the search string and > then compounding my own sql string by working through the array. > > >From my example below, you can see I use a foreach to loop through the > array. Arguably I could first determine the amount of elements in the > array and then use a for instead of a foreach, but I'm not sure if that > will help ( will probably need a switch instead if you want to work with > the sheer array elements), however, the if statement inside the loop is > meant to "strip" out "the" and "and", meaning that it won't much help to > use that approach anyway. > > Anyway, as you can see my problem lies with the SQl when the last > element is reached, then it should NOT add another "and" or "or". > > My attempts at "backtracking" the $sql string/array and start writing > the end part of the string obviously fails. > > Any help with my "logic", ie, how do/would you guys do this? > > Thanks > > > $table_name = "test"; > if ($_POST[any_all] == "any") { > $logic = "or"; > } > elseif ($_POST[any_all] == "all") { > $logic = "and"; > } > > $string = $_POST[text]; > $phrases = explode(" ", $string); > > $sql = "select * from $table_name where "; > > foreach ($phrases as $key=>$val) { > if (($val != "the") && ($val != "and")) { > $sql.= "name like '%$val%' $logic"; > } > } > > $length = strlen($sql); > $newlen = $length - 4; > $sql[$newlen].= " order by name"; > echo $sql; > > > > -- > PHP General Mailing List (http://www.php.net/) > To unsubscribe, visit: http://www.php.net/unsub.php > > Try this $left = array(); foreach ( $phrases as $k => $v ) { if (in_array($v, array('the','and'))) { $left[] = "name like '% ".addslashes($val)." %' {$logic} "; } } $where = join ( '', $left ); Jim Lucas -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php