简体   繁体   中英

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

Probably the most straightforward way is to use in_array() .

$a = [1, 2, 4];

for ($i = 1; $i <= 4; $i++) { 
    echo $i.'. '.(in_array($i, $a) ? 'true' : 'false').PHP_EOL; 
}

Here is a working example .

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/>";
}

The values in your array: $a = array(1, 2, 4) will not correspond to the $i in your for loop when you use $a[$i] , because the value inside the square brackets refers to the key of the array, not to the value.

An array in PHP is an ordered map, with keys corresponding to values. When you define an array of values without assigning keys, like $a = array(1, 2, 4) , PHP automatically creates integer keys for each of the values, beginning with zero, so in effect you are creating this array:

[0 => 1, 1 => 2, 2 => 4]

With the code you showed, you should be getting an undefined offset notice for 4 as well as 3.

If your array is sorted, one way to check for missing elements in your sequence is to check the current value of the array for each increment of your for loop, and move to the next element when a value matches.

$a = array(1,2,4);

for ($i=1; $i <= 4; $i++) {
    if (current($a) == $i){
        echo "$i: true".PHP_EOL;
        next($a);
    } else {
        echo "$i: false".PHP_EOL;
    }
}

The array must be sorted for this to work. If it is not in order as it is in your example, you can sort it with sort($a); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM