Jump to content

array() + unset() = undefined offset


gatzke

Recommended Posts

Using the following code:

 

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

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

 

gives the following error:

 

Notice: Undefined offset: <offset> in <directory>\<file>.php on line 7

Link to comment
Share on other sites

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]);
}
?>

Link to comment
Share on other sites

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++) {...

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.