简体   繁体   中英

Undefined offset 0 but nothing is undefined in var_dump

I'm getting a lot of errors with arrays lately and I cant seem to figure this one out at all.

I get the error:

Undefined offset 0

So of course that means that the index doesn't exist.

Now the next thing I did after this error, I var_dump the arrays.

First I'll show you some code:

var_dump($array1);
var_dump($array2);

for($i = 0; $i < count($array1); $i++){
   var_dump($i);
}

Note: The amount of values in $array1 and $array2 are the same. So counting 1 array and using it in the for will work for both

I try to use $array1[$i] and $array2[$i] in the for but when I use that, I get the error.

So the results of the var_dump are:

array(2) {
  [0]=>
  string(5) "value1"
  [1]=>
  string(5) "value2"
}

array(2) {
  [0]=>
  string(5) "value1"
  [1]=>
  string(5) "value2"
}

int(0)
int(1)

The error comes from: var_dump($array2[$i]);

The way I get the array:

$array2=array_values(Input::get('array2'));

and the checkboxes:

<input type="checkbox" name="array2[]" value="value">

What is undefined here? To my understanding, $array2[$i] should work right? What am I doing wrong?

you can just do

foreach($array1 as $key => $value){
    if (isset($array2[$key])){
        // do stuff
    }
}

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