user3732216 user3732216 - 3 months ago 9
PHP Question

For Loop Display Fact

I'm trying to figure out why I am getting a undefined offset of 1 for this for loop I'm writting. I have an array ($facts) that has specific key values pairs and I'm trying to see if on each iteration the $i matches one of the keys in the array. If the key isset and in the array I need to display the value of that key.

for ($i = 1; $i <= 100; $i++) {
if (isset($i) && in_array($i, $facts[$i])) {
echo $facts[$i];
}
echo $i;
}


UPDATE: Use the function isset to test if the incremented value equals one of the keys in the $facts array. If there is a key that matches, display the value after the number.

Answer

I think this is the correct way of checking (removing the in_array()).

for ($i = 1; $i <= 100; $i++) {
    echo $i; // Now the number is first.
    if (isset($facts[$i])) {
        // This is only echoed if $i exists as a key.
        echo $facts[$i];
    }
}

If you only want to show the number if the fact exists, move echo $i inside the if-statement (or better yet, use foreach($facts as $key => $value) in that case).

Comments