Jump to content

array() + unset() = undefined offset


gatzke

Recommended Posts

This is a simple problem.

 

You are recounting your array, on each loop.  So you will never get more than 3 returned values.

 

On top of this, you are removing the array keys, but you aren't re-ordering the keys.  So, at times your array keys would look like $qwe[0], $qwe[2], $qwe[4].

 

Now if the rand() function returned 3, you would get an un-defined index, because the key no longer exist in the array.

 

Simple fix, is to run it through array_values, to re-order the keys.

<?php

$qwe = array('a','b','c','d','e');

for($i=0; $i<sizeof($qwe); $i++) {
$asd = rand(0, sizeof($qwe)-1);
$qwe = array_values($qwe);
echo $qwe[$asd];
unset($qwe[$asd]);
}
?>

This is a simple problem.

 

You are recounting your array, on each loop.  So you will never get more than 3 returned values.

 

On top of this, you are removing the array keys, but you aren't re-ordering the keys.  So, at times your array keys would look like $qwe[0], $qwe[2], $qwe[4].

 

Now if the rand() function returned 3, you would get an un-defined index, because the key no longer exist in the array.

 

Simple fix, is to run it through array_values, to re-order the keys.

<?php

$qwe = array('a','b','c','d','e');

for($i=0; $i<sizeof($qwe); $i++) {
$asd = rand(0, sizeof($qwe)-1);
$qwe = array_values($qwe);
echo $qwe[$asd];
unset($qwe[$asd]);
}
?>

 

I just noticed you had started to answer my question before I edited my post. I changed

sizeof($qwe)

to "5" which also gave the error but was fixed by using your suggestion. Leaving

sizeof($qwe)

in tact results in only 3 letters being printed, so hard coding or copying the original size of $qwe into another variable does the trick:

$qwe = array('a','b','c','d','e');
$sizeofqwe = sizeof($qwe);

for($i=0; $i<$sizeofqwe; $i++) {...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.