refiking Posted February 4, 2010 Share Posted February 4, 2010 I have a script that takes forever to run. Is there any way I can optimize this? I want to check to see if $desc contains any of the values in $desc_array. If so, I just want to echo $dbtime. Here's what I have right now: $dbtime = date('m/d/y h:i A',strtotime(str_replace(',','',$datetime).$tadj)); $desc_array = array("maintenance", "theatre", "golfing", "fishing"); $i = 0; foreach ($desc_array as $desc_filter) { $pos = strpos($desc, $desc_filter); if($pos !== false){ $i++; } } if($i > 0){ echo $dbtime.'<br>'; } Link to comment https://forums.phpfreaks.com/topic/190978-best-way-to-search-each-subtring-in-array/ Share on other sites More sharing options...
roopurt18 Posted February 4, 2010 Share Posted February 4, 2010 I'm not sure it'll be any faster. But you could try: // $haystack contains text to search // $terms is array of terms to search $haystack = explode( ' ', $haystack ); $haystack = array_unique( $haystack ); $found = array_intersect( $haystack, $terms ); print_r( $found ); Link to comment https://forums.phpfreaks.com/topic/190978-best-way-to-search-each-subtring-in-array/#findComment-1007093 Share on other sites More sharing options...
refiking Posted February 4, 2010 Author Share Posted February 4, 2010 How would this code be implemented, though? if(array_intersect( $haystack, $terms )){ echo $dbtime; } Link to comment https://forums.phpfreaks.com/topic/190978-best-way-to-search-each-subtring-in-array/#findComment-1007095 Share on other sites More sharing options...
roopurt18 Posted February 4, 2010 Share Posted February 4, 2010 if( count( array_intersect( $haystack, $terms ) ) > 0 ) echo $dbtime; Link to comment https://forums.phpfreaks.com/topic/190978-best-way-to-search-each-subtring-in-array/#findComment-1007111 Share on other sites More sharing options...
refiking Posted February 5, 2010 Author Share Posted February 5, 2010 Didn't return $dbtime. Here's the code: $haystack = explode( ' ', $desc); $haystack = array_unique( $haystack ); if(count(array_intersect($haystack, $desc_array)) > 0 ){ echo $dbtime; } else{ echo 'nope<br>'; } Link to comment https://forums.phpfreaks.com/topic/190978-best-way-to-search-each-subtring-in-array/#findComment-1007124 Share on other sites More sharing options...
roopurt18 Posted February 5, 2010 Share Posted February 5, 2010 What's this print: <?php $haystack = explode( ' ', $desc); $haystack = array_unique( $haystack ); echo '$haystack<pre>' . print_r( $haystack, true ) . '</pre>'; echo '$desc_array<pre>'.print_r( $desc_array, true ).'</pre>'; if(count(array_intersect($haystack, $desc_array)) > 0 ){ echo $dbtime; } else{ echo 'nope<br>'; } ?> Link to comment https://forums.phpfreaks.com/topic/190978-best-way-to-search-each-subtring-in-array/#findComment-1007135 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.