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?
@stuartherbert
Copy link

$bar = [
1 => "hello",
2 => "goodbye",
];

would trigger the problem.

@adamwathan
Copy link

A string key would blow this up:

$bar = ['hello' => 'world'];
count($bar); // 1
$bar[0]; // Blows up

@stuartherbert
Copy link

$bar = [
"foo" => "trout"
];

would also trigger the problem.

@kingcrunch
Copy link

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

http://3v4l.org/JsUIJ

$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"
}
*/

@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