T888 T888 - 9 months ago 37
PHP Question

'Undefined Offset 1' error


require "connect.php";

$file = "./myFile2.txt";
$document = file_get_contents($file);

$lines = explode("\n",$document);

foreach($lines as $newline) {

$arr = explode('Order Number: ', $newline);
$important = $arr[1]; //getting an error here (undefined offset 1)

echo $important;

$art = explode('Total Price: ', $newline);
$first = $art[1]; //getting an error here (undefined offset 1)

echo $first;



myFile2.txt reads as follows:

Order Number: 12345
Total price: 60$

The code outputs both '12345' and '60$' yet displays an 'Undefined Offset: 1' after each echo.

How can i fix this? Do i have to account for the return key that separates order number and total price?

Answer Source

You're exploding Order Number: 12345 as :- explode('Order Number: ', $newline); and therefore your required value is in the 0 offset of your array.

If you had exploded in this way :-

explode(':', $string); //$string = Order Number:12345 

Then you would not get the error.

So try replacing :-

$important = $arr[1];


$important = $arr[0];