Skip to content

Instantly share code, notes, and snippets.

@chartjes
Last active August 29, 2015 14:10
Show Gist options
  • Save chartjes/3b4c4814a5a0ec8f4904 to your computer and use it in GitHub Desktop.
Save chartjes/3b4c4814a5a0ec8f4904 to your computer and use it in GitHub Desktop.
Fun with PHP Arrays
// Given the following code
function foo(array $bar) {
$barCount = count($bar);
for ($i = 0; $i < $barCount; $i++) {
$baz = explode(Validator::DELIMITER, $bar[$i]);
unset($bar[$i]);
foreach ($bar as $val) {
$val = trim($val);
if ($val !== '') {
$bar[] = $val;
}
}
}
return $bar;
}
// What would have to be in $bar for it to trigger an
// "offset does not exist error" on the line with explode?
@kieranajp
Copy link

unset($bar[$i]);

I think this may be causing the problem; once you've unset an item in the array, $barCount is > than the actual number of items in the array, no?

@Perturbatio
Copy link

use a foreach on the outer loop? unsetting inside a foreach is safe (IIRC)

@kieranajp
Copy link

Yeah I also think foreach would solve it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment