Jump to content

Best Way To Search Each Subtring In Array


refiking

Recommended Posts

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>'; }

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 );

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>';
	}
?>

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.