3

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
1
  • you can get last number of array by end($a) and put it in the for function Commented Aug 21, 2016 at 4:00

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.