arrays - Undefinied offset php -
i trying run code:
$file = fopen($txtfile, "r"); while(!feof($file)) { $line = fgets($file); $pieces = explode(",", $line); $date = $pieces[0]; $open = $pieces[1]; $high = $pieces[2]; $low = $pieces[3]; $close = $pieces[4]; $volume = $pieces[5];
}
and notice:
undefined offset: 1 in ...
undefined offset: 2 in ...
undefined offset: 3 in ...
undefined offset: 4 in ...
undefined offset: 5 in ...
i thankful, if tell me, why so.
as stephen said looks array not expecting be, there few things can do.
try using
var_dump($pieces)
and take @ array contains. thing can prevent errors , more defensive in code following:
$file = fopen($txtfile, "r"); while(!feof($file)) { $line = fgets($file); $pieces = explode(",", $line); if(isset($pieces[0])) $date = $pieces[0]; if(isset($pieces[1])) $open = $pieces[1]; if(isset($pieces[2])) $high = $pieces[2]; if(isset($pieces[3])) $low = $pieces[3]; if(isset($pieces[4])) $close = $pieces[4]; if(isset($pieces[5])) $volume = $pieces[5]; } }
alternatively in case can check length of $pieces, use may better , shorter, this:
$file = fopen($txtfile, "r"); while(!feof($file)) { $line = fgets($file); $pieces = explode(",", $line); if(sizeof($pieces) != 6){ //handle case here } else { $date = $pieces[0]; $open = $pieces[1]; $high = $pieces[2]; $low = $pieces[3]; $close = $pieces[4]; $volume = $pieces[5]; } }
this ensures variables exist before try them , avoid issue of undefined index.
Comments
Post a Comment