Skip to content
PHP Logo

How can arrays be manually compared using a for loop in PHP?

To manually compare arrays using a for loop in PHP, you can iterate through each element of both arrays and compare them one by one. You can use a for loop to iterate over the arrays and compare the values at each index. If all elements match, the arrays are considered equal. If any element does not match, the arrays are considered not equal.

php
$array1 = [1, 2, 3, 4];
$array2 = [1, 2, 3, 4];

// Check if arrays have the same length
if(count($array1) != count($array2)) {
    echo "Arrays are not equal";
} else {
    $equal = true;
    for($i = 0; $i < count($array1); $i++) {
        if($array1[$i] != $array2[$i]) {
            $equal = false;
            break;
        }
    }
    
    if($equal) {
        echo "Arrays are equal";
    } else {
        echo "Arrays are not equal";
    }
}