exoot
exoot

Reputation: 13

PHP for loop will affect the page load speed?

$categories = array("google","adobe","microsoft","exoot","yahoo");
$sql='google,exoot,adobe';//from mysql_query
$categs = explode(",",$sql);

for($x=0;$x<count($categs);$x++){
    for($y=0;$y<count($categories);$y++){
        if($categs[$x] == $categories[$y]){
            $str .= $y.",";
        }
    }
}

echo str; // 0,3,1,

Will this code will affect page render time? Can I do it using any other fast methods?

Thanks in advance.

Upvotes: 1

Views: 258

Answers (5)

user259061
user259061

Reputation: 13

$arrCategories = array("google","adobe","microsoft","exoot","yahoo");
$sql='google,exoot,adobe';//from mysql_query
$arrCategs = explode(",",$sql);
$arrAns = array();

for($i = 0, $intCnt = count($arrCategs); $i <= $intCnt; $i++) {
    if(in_array($arrCategs[$i],$arrCategories)) {
        $arrAns[$arrCategs[$i]] = array_search($arrCategs[$i], $arrCategories);
    }
}

print "<pre>";
print_r($arrAns);
print "</pre>";

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816600

I don't think that str_replace is a faster method than all the array functions but another possible solution is:

$categories = array("google","adobe","microsoft","exoot","yahoo");
$sql='google,exoot,adobe';//from mysql_query

foreach($categories as $i=> $c) {
     $sql = str_replace($c, $i, $sql);   
}

Upvotes: 0

RJD22
RJD22

Reputation: 10340

yes it will since you are looping in a loop.

Best thing is to check with in array:

$categories = array("google","adobe","microsoft","exoot","yahoo");
$sql='google,exoot,adobe';//from mysql_query
$categs = explode(",",$sql);
$str = array();

foreach($categs as $id => $categs_check)
{
    if(in_array($categs_check, $categories))
    {
        //its better to put it into a array and explode it on a later point if you need it with comma.
        $str[] = $id;
    }
}

I'm not completely sure what you are trying to do but it should be something like the above

Upvotes: 0

Karsten
Karsten

Reputation: 14642

$str = implode(',', array_keys(array_intersect($categories, $categs)));

Upvotes: 2

cletus
cletus

Reputation: 625147

You can use array_intersect() to find the common items and then use implode() to construct a comma-separated list:

Str = implode(',', array_intersect($categories, $categs)) . ',';

Unless you're dealing with a large number of items (thousands) it won't affect page speed. The one issue is that this intersection is O(n2). Putting the values into keys could speed it up considerably as that changes lookup time from O(n) to near O(1) making the whole operation O(n).

Upvotes: 0

Related Questions