views:

101

answers:

5
$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.

+2  A: 
$str = implode(',', array_keys(array_intersect($categories, $categs)));
Karsten
This is not what he wants. Notice how he concatenates the INDEX and not the VALUE.
LiraNuna
it returns string (google,adobe,exoot) instead for number of the array (0,3,1,)
exoot
added array_keys around array_intersect to return concatenated INDEXES, thank you LiraNuna
Karsten
its working..thank you Karsten and LiraNuna
exoot
Mark it as correct answer, then, exoot.
LiraNuna
ok done,LiraNuna..
exoot
A: 

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

cletus
A: 

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);   
}
Felix Kling
A: 

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

RJD22
A: 

$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 "

";
print_r($arrAns);
print "
";