How can you easily avoid getting this error/notice:
Notice: Undefined offset: 1 in /var/www/page.php on line 149
... in this code:
I often come across this issue, so I wanted a function that allowed something nicer syntactically without unnecessarily padding the array or string.
// Put array entries in variables. Undefined index defaults to null
function toVars($arr, &...$ret)
{
$n = count($arr);
foreach ($ret as $i => &$r) {
$r = $i < $n ? $arr[$i] : null;
}
}
// Example usage
toVars(explode('|', $value), $func, $field);
For my purposes, I'm usually working with an array, but you could write a similar function that includes the explode function, like this...
// Explode and put entries in variables. Undefined index defaults to null
function explodeTo($delimiter, $s, &...$ret)
{
$arr = explode($delimier, $s);
$n = count($arr);
foreach ($ret as $i => &$r) {
$r = $i < $n ? $arr[$i] : null;
}
}
// Example usage
toVars('|', $value, $func, $field);
Requires PHP5.6 or above for variadic function: http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list