Last active
August 29, 2015 14:10
-
-
Save chartjes/3b4c4814a5a0ec8f4904 to your computer and use it in GitHub Desktop.
Fun with PHP Arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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? |
Probably $bar
is not continuously indexed like in
$bar = [0 => 'x', 2 => 'y'];
One reason could be, that for example array_unique()
does not reset the point
$bar = [0 => 'x', 1 => 'y', 2 => 'y'];
$bar = array_unique($bar);
$bar[] = 'z';
var_dump($bar);
/*
array(3) {
[0]=>
string(1) "x"
[1]=>
string(1) "y"
[3]=>
string(1) "z"
}
*/
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?
use a foreach on the outer loop? unsetting inside a foreach is safe (IIRC)
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
$bar = [
"foo" => "trout"
];
would also trigger the problem.