traq
01-18-2011, 04:53 AM
hello, just a curiosity (I have a workaround for the problem; but I'd like to figure out what's going on):
Say I have this function:
function whereClause($words){
foreach($words as $k=>$v){ if(!empty($v)){ $words[$k] = "`field` LIKE '%$v%'"; } }
$where = "WHERE ".implode(' OR ',$words);
print $where;
}
$arr = array('these','are','some','words');
whereClause($arr); // works great. outputs:
// WHERE `field` LIKE '%these%' OR `field` LIKE '%are%' OR `field` LIKE '%some%' OR `field` LIKE '%words%'
BUT, as you may expect, if $words is a string (e.g., only one word), you have problems- foreach and implode both require arrays. I can solve this by casting $words as an array:
function whereClause($words){
foreach((array)$words as $k=>$v){ if(!empty($v)){ $words[$k] = "`field` LIKE '%$v%'"; } }
$where = "WHERE ".implode(' OR ',(array)$words);
print $where;
}
$str = 'these';
whereClause($str); // kinda works - no errors, but this is the output:
// WHERE `hese
wth did that come from?
even if (array)$words as $k=>$v is treating "t" as the key ($k), why is it losing the "`field` LIKE '% %'" part?
Thanks for any insights
(things that bug me just bug me)
Say I have this function:
function whereClause($words){
foreach($words as $k=>$v){ if(!empty($v)){ $words[$k] = "`field` LIKE '%$v%'"; } }
$where = "WHERE ".implode(' OR ',$words);
print $where;
}
$arr = array('these','are','some','words');
whereClause($arr); // works great. outputs:
// WHERE `field` LIKE '%these%' OR `field` LIKE '%are%' OR `field` LIKE '%some%' OR `field` LIKE '%words%'
BUT, as you may expect, if $words is a string (e.g., only one word), you have problems- foreach and implode both require arrays. I can solve this by casting $words as an array:
function whereClause($words){
foreach((array)$words as $k=>$v){ if(!empty($v)){ $words[$k] = "`field` LIKE '%$v%'"; } }
$where = "WHERE ".implode(' OR ',(array)$words);
print $where;
}
$str = 'these';
whereClause($str); // kinda works - no errors, but this is the output:
// WHERE `hese
wth did that come from?
even if (array)$words as $k=>$v is treating "t" as the key ($k), why is it losing the "`field` LIKE '% %'" part?
Thanks for any insights
(things that bug me just bug me)