如何使用for循环逐元素地比较两个数组?

This is a mock example of my problem.

The 'for loops' will be contained inside a while loop, if that matters.

The code below should compare every element of each array and echo out the element that is the same. In this case 'Fat'.

However, the code is not working and I can't figure out why. I'm sure it's a simple fix, but I can't seem to find it.

$searchValue="Bob Is Fat";
$explode = explode(' ', $searchValue);           //turns $searchValue into an array
$tags_cnt = count($explode);                     //counts elements in the array

$result_tag = array("Volvo", "Skinny", "Fat");   //creates an array
$row_cnt = count($result_tag);                   //counts elements in array


        for($i=0; $i<$tags_cnt-1; $i++) {
            for($x=0; $x<$row_cnt-1; $x++) {
                if ($result_tag[$x] == $explode[$i]) {        
                    echo $explode[$i];
                }   
            } //2 forloop                                                               
        } //1 forloop

Remove the -1, the value of $tags_cnt-1 is 2, when start the for the value $i is 0, in the second loop the value for the $i is 1, the condition says that the loop works until $i<$tags_cnt so, in the second loop 1<2 and is the last one because in the next loop don't match with the condition.

<?php
$searchValue="Bob Is Fat";
$explode = explode(' ', $searchValue);           //turns $searchValue into an array
$tags_cnt = count($explode);                     //counts elements in the array

$result_tag = array("Volvo", "Skinny", "Fat");   //creates an array
$row_cnt = count($result_tag);                   //counts elements in array


        for($i=0; $i<$tags_cnt; $i++) {
            for($x=0; $x<$row_cnt; $x++) {
                if ($result_tag[$x] == $explode[$i]) {        
                    echo $explode[$i];
                }   
            } //2 forloop                                                               
        } //1 forloop
?>

Or in your first for:

for($i=0; $i<=$tags_cnt-1; $i++)

and in the second:

for($x=0; $x<=$row_cnt-1; $x++)

Hope works for you.

try foreach for eliminating array key issues

foreach($explode as $explodeValue){
    foeach($result_tag as $tag){
        if($tag == $explodeValue){
            echo $explodeValue;
        }
    }
}

i think this should work.

Why do you need loops here??

$searchValue = "Bob Is Fat";
$explode = explode(' ', $searchValue);

$result_tag = array("Volvo", "Skinny", "Fat");

var_dump(array_intersect($explode, $result_tag));