PHP Question

How can I compare a loop value to an array value that is not sequentially the same?

I have a loop from 1 to 4, and I have an array which contain 1,2, and 4, but misses the number 3. How do I put or replace the missing 3 into 0 as my only thought to solve my problem, or get all the same values and then compare both sides? Because I need to compare both sides if it's same or not.

With this code, I'm getting the error: "undefined offset 3".

$a = array(1,2,4);
for ($i=1; $i <= 4; $i++) {
if ($i==$a[$i]) {
echo 'true';
} else {
false;
}
}


Is there other way to compare all those that have same value like

1 & 1 = true
2 & 2 = true
3 & = false
4 & 4 = true


And display something like

1. true
2. true
3. false
4. true

Answer

Something like that :

$a = array(1,2,4);
$flipped = array_flip($a);
for($i = 1; $i <= 4; $i++){
    $res[$i]="false";
    if(array_key_exists($i, $flipped)){
        $res[$i] = "true";
    }
}

foreach($res as $key=>$value){
    echo $key.". ".$value."<br/>";
}
Comments