1

I have an array like this

$arr = array(
    array("index"=>"5"),
    array("index"=>"7"),
);

wanna find value using looping and set result like this

 /** OUTPUT
    '1 false'
    '2 false'
    '3 false'
    '4 false'
    '5 true'
    '6 false'
    '7 true'
 **/

I try my code like this, but not work

for($i = 1; $i <= max(array_column($arr, 'index')); $i++){
    if(in_array($i, $arr[$i]){
        echo 'true '.$i;
    }else{
        echo 'false'.$i;   
    }
}

thanks

2
  • You have errors in your code; you're missing a closing parenthesis in if(in_array($i, $arr[$i]){ and $i == max should be $i = max. You were close with the general idea, though. You just need to use array_column($arr, 'index') instead of $arr[$i]. Commented Feb 19, 2021 at 16:52
  • ohh my bad.. $i <= max but output is still false if index 5 and index 7 Commented Feb 19, 2021 at 17:00

2 Answers 2

2

You should try something like:

for ($i = 1; $i <= max(array_column($arr, 'index')); $i++) {
    if (in_array($i, array_column($arr, 'index'))) {
        echo $i . 'true' . '\n';
    } else {
        echo $i . ' false' . '\n';   
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You were close to the solution but your main error was here:

if(in_array($i, $arr[$i]){

Here you try to access the index $i in your original array $arr. That array only has two of them - 0 and 1. On the other hand, your loop will run from 1 to 7, causing "Undefined index" notices for anything greater than 1.

You seem to be familiar with the array_column function since you use it to determine how far your loop should go:

max(array_column($arr, 'index'))

And this is exactly what you should compare against. This returns a simple array [5, 7] which can then be used as a haystack value for in_array:

$arr = array(
    array("index"=>"5"),
    array("index"=>"7"),
);
$indices = array_column($arr, 'index'); // store it as you have to use it multiple times
for ($i = 1; $i <= max($indices); $i++) {
    if (in_array($i, $indices)) {
        var_dump('true '.$i);
    } else {
        var_dump('false '.$i);
    }
}

This will output:

'false 1'
'false 2'
'false 3'
'false 4'
'true 5'
'false 6'
'true 7'

Comments

Your Answer

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