Undefined offset error

[php] #snippet: Throws error on L. 167 “Undefined offset:” (Code under transition php4 -> php5)

$a = Array(); // a list of country choices and their 2-char codes

$a[" "] = ‘’; // first element is blank - forces user to a selection

$fh = fopen($_SERVER{‘DOCUMENT_ROOT’} . ‘/auxlib/web07/InclReq/kvpisow2.txt’, “r”);

// $fh is an associative array of $2char_abbreviation => $countryname. Here are the 1st 4 entries
// Key US Value United States
// Key AF Value Afghanistan
// Key AL Value Albania
// Key AG Value Algeria
// …

while ($buffer = fgets($fh))
{
$kvp = preg_split ("/[\s,]+/", $buffer); // Split buffer on any combination of spaces or commas.
#L. 167 next line#
$a["$kvp[1]"] = $kvp[3] . " " . $kvp[4] . " " . $kvp[5] . " " . $kvp[6] . " " . $kvp[7] . " "
. $kvp[8];
}
fclose ($fh);

[/php]

Shouldn’t the first call, $a[“ “]=’’;, establish the [0] reference and thus set the offset? $a[0] = ‘’; doesn’t work either.

Using $a = array($key=>0, $value=>’’);
instead of $a = array();
doesn’t eliminate the ‘undefined offset’ error either.

Is there something I’m missing in the transition php4->php5?

RECAP / UPDATE
Main program throws error ‘Undefined index: invoiceNo’ error, where ‘invoiceNo’ is the first array element of a list.
Web offers 3 solutions:

  1. the referenced var is not an array;

  2. the referenced array has not been initialized;

  3. change error settings; e.g. ,error_reporting = E_ALL & ~E_NOTICE | ~E_DEPRECATED,
    All 3 are tested below without eliminating the ‘Undefined index’ error thrown.
    TEST SCRIPT: attmp2initArray.php
    [php]
    error_reporting(E_ALL & ~E_NOTICE | ~E_DEPRECATED); //3)

    $buffer = array(); //1)

    echo (is_array($buffer) ? 'L.12 $buffer is an array
    ’ : 'L.12 $buffer is not an array
    '); //1)

    $fh = fopen($_SERVER{‘DOCUMENT_ROOT’} . ‘/auxlib/web07/InclReq/kvpisow2.txt’, “r”);

    $buffer = fgets($fh);

    echo (is_array($buffer) ? 'L.18 $buffer is an array
    ’ : 'L.18 $buffer is not an array
    '); //1)

    if (is_array($buffer)){ //2)
    foreach($buffer as $k => $v) {if(!isset($v)) $v = null ;}
    } else {
    echo “$buffer” , "
    L.23 $buffer is an array
    ";
    }
    $buffer = fgets($fh);
    reset($buffer); echo ‘!L.26 reset fails, $buffer is now a string!
    ’; //1)

    echo (is_array($buffer) ? 'L.28 $buffer is array
    ’ : 'L.28 $buffer is not an array
    ');

    echo 'L.30 Although not recognized as an array note… var_dump does …

    ', var_dump($buffer) , ‘
    ’;
    //1) L.30[/php]

I’m really stuck for lack of new intrepretation of my problem, which is …

FATAL ERROR. ‘Undefined index: invoiceNo’ ,where ‘invoiceNo’ is the 1st entry in an associative array, $buffer().
In trying to find a way to correct the ‘undifened index’, I’ve tried to reset it without success. The result still throws an undefined index. So I wrote a few lines of code and then inserted is_array() tests to see when an array is no longer recognized as an array, which would (I presume) throw the error. (This effort is shown in the last reply herewith.) The problem appears to happen on populating the newly defined array.

I defined an array $buffer (it tested as an array); then populated it with the contents of kvpisow2.txt (now it is no longer an array); then I tried to set each $value = null as though initializing an array (of course it didn’t work); then tried a few more fruitless efforts.

Is there a way to convert a string to an associative array and reset its index? Or is there a better solution?
This problem has arisin in a 10yr old php4 scrip, that always worked, and now in its php5 version throws an error (why? I don’t know)

Any suggestions on how to resolve this problem are greatly appreciated.

usit

Where is the code that references the ‘invoiceNo’ index?

Good to see you back m@tt; you’ve been a big help to my learning process.

Most comments have been removed. This is a section of the larger main code. It runs with the following output: (The script has some residual, trivial code I used to understand what happens to an array.) L. 144 is marked

##<<.
----output----
L8. RGSTRTN_06.php Tuesday 05th of March 2013 11:09:11 AM 
Tuesday 05th of March 2013 11:09:11 AM L.156 $buffer is an array 

Key US Value United States L. 166 Key US Value United States is an array 
L.169 $buffer is not an array 

string(26) "Key AF Value Afghanistan 
"

Fatal error: Uncaught exception 'ErrorException' with message 'Undefined offset: 5' in /home/vg011web00/68/65/2926568/web/auxlib/usit2013/snip_test.php:134 Stack trace: #0 /home/vg011web00/68/65/2926568/web/auxlib/usit2013/snip_test.php(134): exception_error_handler(8, 'Undefined offse...', '/home/vg011web0...', 134, Array) #1 {main} thrown in /home/vg011web00/68/65/2926568/web/auxlib/usit2013/snip_test.php on line 134

[php]<?php //snip_test.php
// www.u-sit.net/auxlib/web07/HTMLpages/RGSTRTN_06.php
session_start();

include_once ($_SERVER['DOCUMENT_ROOT'] . '/lib/php/cnnct2mysql.php');

$time_stamp =  date('l dS \of F Y h:i:s A ');

echo 'L8. RGSTRTN_06.php ’ .date(‘l dS \of F Y h:i:s A ‘),’

’;
$notify_email = ‘[email protected]’;

?>

RGSTRTN_06.php Send Registration data to DBs. Includes mailing of freebies & June07 US Postal rates <?PHP if (!session_is_registered("counted")) {mysql_query("UPDATE hitcounter SET count=(count + 1) WHERE count_id=1"); session_register("counted"); } error_reporting (E_ALL ^ E_NOTICE); //echo ($_SERVER{'DOCUMENT_ROOT'}); // /home/68/65/2926568/web include_once ($_SERVER{'DOCUMENT_ROOT'} . '/auxlib/usit2013/SMTP4PHP.php'); /* $hit_query = "SELECT count FROM hitcounter"; $hit_result = mysql_query($hit_query); $hits = mysql_fetch_assoc($hit_result); foreach ($hits as $key => $value){ $hit = $value; //echo "key = $key, ID = $ID
"; } */ echo date('l dS \of F Y h:i:s A '); // // $fp = fsockopen ('www.sandbox.paypal.com', 80, $errno, $errstr, 30); foreach ($_POST as $key => $value) { echo (isset($_POST["submit"]) ? $key= $value : null) . '
'; } /* $invoiceNo = $_POST['invoiceNo']; $amount = $_POST['amount']; $item_name = $_POST['item_name']; $email = $_POST['email']; $first_name = $_POST['first_name']; $last_name = $_POST['last_name']; $address1 = $_POST['address1']; $address2 = $_POST['address2']; $city = $_POST['city']; $state = $_POST['state']; $zip = $_POST['zip']; $country = $_POST['country']; $mc_gross = $_POST['mc_gross']; $mc_fee = $_POST['mc_fee']; $tax = $_POST['tax']; $s_h = $_POST['S_H']; $affiliation = $_POST['affiliation']; $degree = $_POST['degree']; $occupation = $_POST['occupation']; $specialty = $_POST['specialty']; $Nwsltr = $_POST['Nwlstr']; $USIT_txt = $_POST['USIT_txt']; $USIT_ovr_En = $_POST['USIT_ovr_En']; //use 'e', 's', 'es' ? $USIT_ovr_Sp = $_POST['USIT_ovr_Sp']; $HI_txt = $_POST['HI_txt']; $USIT_HI = $_POST['USIT_HI']; $Nwsl_En = $_POST['Nwsl_En']; $Nwsl_Sp = $_POST['Nwsl_Sp']; $EnNL01_10 = $_POST['EnNL01_10']; $SpNL01_19 = $_POST['SpNL01_19']; $EnNL11_20 = $_POST['EnNL11_20']; $SpNL01_54 = $_POST['SpNL01_54']; $EnNL21_30 = $_POST['EnNL21_30']; $EnNL31_40 = $_POST['EnNL31_40']; $EnNL41_50 = $_POST['EnNL41_50']; $EnNL51_60 = $_POST['EnNL51_60']; $EnNL61_70 = $_POST['EnNL61_70']; $EnNL71_80 = $_POST['EnNL71_80']; $payment_date = $time_stamp; */ // B. Prepare Country- & State-select tags (Courtesy David Kirol) // $a = array(); // a list of country choices and their 2-char codes $buffer = array(); if (is_array($buffer)) echo 'L.156 $buffer is an array
'; //$a[" "] = ''; // first element is blank - forces user to select one of a displayed list $fh = fopen($_SERVER{'DOCUMENT_ROOT'} . '/auxlib/web07/InclReq/kvpisow2.txt', "r"); $buffer = fgets($fh); if (is_array($buffer)){ foreach($buffer as $k => $v) {if(!isset($v)) $v = null ;} } else { echo "
$buffer L. 166 $buffer is an array
"; } $buffer = fgets($fh); echo (is_array($buffer) ? 'L.169 $buffer is array
' : 'L.169 $buffer is not an array
'); echo '
', var_dump($buffer) , '
'; while ($buffer = fgets($fh)) { $kvp = preg_split ("/[\s,]+/", $buffer); // Split buffer on any combination of spaces or commas. $a["$kvp[1]"] = $kvp[3] . " " . $kvp[4] . " " . $kvp[5] . " " . $kvp[6] . " " . $kvp[7] . " " ##ERROR THROWN Here . $kvp[8]; } fclose ($fh); //////////////////// ++++++++++++++ End of Country prep +++++++++++++ //////////////// ?>

[/php]

For the line you posted (134) it just means that preg_split did not return an array with 5 or more indexes.

You should do a var_dump($kvp) and see what preg_split is actually returning.

Thank you for your interest and quick reply.
var_dump helped.

usit

ps; m@tt,
Why the Fatal error? That sounds like an expected result and not fatal. Until I get rid of the fatal error I won’t be able to compile the program.
usit

The fatal error is an uncaught exception. Something in your code is throwing ErrorException (perhaps you have configured a custom error function with set_error_handler() ??)

When using exceptions you need to wrap your code in try/catch blocks. For example:

[php]
// an exception can be thrown here
try {
throw new ErrorException(‘This is an example exception’);
}
// catch any thrown exceptions
catch(Exception $e) {
exit($e->getMessage());
}
[/php]

If you fix the undefined index error it will also remove the fatal error from the uncaught exception.

Also want to point out that session_is_registered() and session_register() are both deprecated as of PHP 5.3 so you should be using $_SESSION instead.

RIGHT ON w@tt! You hit the nail on the head. The index and offset errors are thrown when the script has …

include_once ($_SERVER{‘DOCUMENT_ROOT’} . ‘/…/SMTP4PHP.php’);

SMTP4PHP.php is a new (to me) smtp mailer: Copyright © 2011 - 2012, Raul IONESCU [email protected], Bucharest, ROMANIA.

After giving up on ever getting phpmailer to work again I switched to this smpt mailer. With your suggestion, I searched for exception_error and found this …

L.33. Searching on ‘ion_er’;
function exception_error_handler($errno, $errstr, $errfile, $errline, $errcontext )
{ throw new ErrorException($errstr, $errno, 0, $errfile, $errline); }

also this …

L.36. set_error_handler(“exception_error_handler”);

Then searching on erro found three more relevant references …

  1. Searching on ‘erro’
    if($expectedResponse && (!preg_match(’/^’.$expectedResponse.’/S’, $smtpResponse)))
    { throw new Exception(‘Unexpected SMTP error! (SMTP command: "’.trim($smtpCommand).’" SMTP response: “’.$smtpResponse.’”)’,(preg_match(’/^(\d{3})/mSU’,$smtpResponse,$m) && is_array($m) && isset($m[0]))?($m[0]):(NULL)); }

  2. if(empty($this->smtpConnect)) { throw new Exception(‘SMTP connection error!’.($errstr)?(’ (’.$errstr.’)’):(’’)); }

  3. if(!stream_socket_enable_crypto($this->smtpConnect, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) { throw new Exception(‘Unexpected TLS encryption error!’); }

It appears, to my untrained eyes, that the exceptions of concern are related to smtp commands, connections, or encryption. I have no idea how the errors (in my main script) could be associated with these smtp issues. The errors occur in the following line of my main:

$kvp = preg_split ("/[\s,]+/", $buffer);     
$a["$kvp[1]"] = $kvp[3] . " " . $kvp[4] . " " . $kvp[5] . " " . $kvp[6] . " " . $kvp[7] . " " . $kvp[8];

Any suggestions on how to proceed?

Thanks for getting me over this huge bump in the road.

usit

:slight_smile:

The error is not related to the SMTP class but it does explain why you are getting an uncaught exception.

set_error_handler(“exception_error_handler”)

Is setting the error handler function for the entire script. That’s why later on you get an ErrorException thrown for an undefined offset.

Your problem is still the same, $kvp[5] is undefined (most likely 6, 7 and 8 are also undefined).

Did you var_dump($kvp) and verify that there are more than 4?

Hi, w@att.
Can’t do a var_dump when stopped by a FATAL error – script doesn’t compile. So did the following:

  1. Reduced the test file, RGSTRTN_06_testA.php, to just enough code to capture the error. (Changed $buffer to $a.)
  2. Put in var_dump($a) following the stuffing of $a with the country code $key, $value pairs, from kvpisow2.txt and before
    while ($a = fgets($fh))
    {
    $kvp = preg_split ("/[\s,]+/", $a); // Split a on any combination of spaces or commas.
    $a["$kvp[1]"] = $kvp[3] . " " . $kvp[4] . " " . $kvp[5] . " " . $kvp[6] . " " . $kvp[7] . " " ##ERROR HERE
    . $kvp[8];
    }
  3. Ran this and get …

-------------------- output of RGSTRTN_06_testA.php ------------------
L.3 RGSTRTN_06_tstA.php Thursday 07th of March 2013 09:26:24 AM
string(28) "Key US Value United States "

Fatal error: Uncaught exception ‘ErrorException’ with message ‘Undefined offset: 5’ in /home/vg011web00/68/65/2926568/web/auxlib/usit2013/RGSTRTN_06_tstA.php:21 Stack trace: #0 /home/vg011web00/68/65/2926568/web/auxlib/usit2013/RGSTRTN_06_tstA.php(21): exception_error_handler(8, ‘Undefined offse…’, ‘/home/vg011web0…’, 21, Array) #1 {main} thrown in /home/vg011web00/68/65/2926568/web/auxlib/usit2013/RGSTRTN_06_tstA.php on line 21
----------------------end of output ------------------------------------
Note that var_dump(a) gets only the first contry code $key, $value pair as string(28)?
4. Unix, cat kvpisow2.txt, shows the file has 4544 bytes, yet var_dump() finds only the first pair.
[php]---------------------- Here’s the script RGSTRTN_06_tstA.php --------------------------------------------------
// RGSTRTN_06_tstA.php

echo 'L.3  RGSTRTN_06_tstA.php   ' . date('l dS \of F Y h:i:s A ' . '<p>');

include_once ($_SERVER{'DOCUMENT_ROOT'} . '/.../SMTP4PHP.php');

$a 	= array();

$fh = fopen($_SERVER{'DOCUMENT_ROOT'} . '/.../kvpisow2.txt', "r");

$a = fgets($fh);

echo ‘

’ . var_dump($a) . ‘

’;

while ($a = fgets($fh)) 
	{
$kvp = preg_split ("/[\s,]+/", $a);      // Split a on any combination of spaces or commas.
$a["$kvp[1]"] = $kvp[3] . " " . $kvp[4] . " " . $kvp[5] . " " . $kvp[6] . " " . $kvp[7] . " " ##ERROR HERE
. $kvp[8];
	}	     
	
fclose ($fh);	

//------------------------------------- end of RGSTRTN_06_testA.php ------------------------
[/php]

*One thing (of several) I don’t get is after defining a()=array, var_dump claims that $a() is a string?
*I have thought all along that the latter parts of $kvp[5] only get initialized with real bytes when the country has a long multipart name. This was always satisfactory with PHP4.
I could probably put in a ternary conditional for each $kvp[], that tests for being initialized and sets it to null if not. Would this still throw an error?

Thanks much for your continued interest.

usit

You are continuously overwriting $a. It can’t be your line buffer and your results array.

What happens when you run this code:

[php]

<?php echo 'L.3 RGSTRTN_06_tstA.php ' . date('l dS \of F Y h:i:s A ' . '

'); include_once ($_SERVER{'DOCUMENT_ROOT'} . '/.../SMTP4PHP.php'); $results = array(); try { $fh = @fopen($_SERVER{'DOCUMENT_ROOT'} . '/.../kvpisow2.txt', "r"); if ($fh) { while(($buffer = fgets($fh, 4096)) !== false) { $kvp = preg_split ("/[\s,]+/", $buffer); $results[$kvp[1]] = $kvp[3] . " " . $kvp[4] . " " . $kvp[5] . " " . $kvp[6] . " " . $kvp[7] . " " . $kvp[8]; } fclose($fh); } } catch(Exception $e) { exit('Exception caught: ' . $e->getMessage()); } var_dump($results); ?>

[/php]

Your code produces …

L.3 watt_test.php Thursday 07th of March 2013 02:42:15 PM
Exception caught: Undefined offset: 6

Right, so you still have a problem with your string. Can you show me the contents of kvpisow2.txt?

w@tt; Here’s the contents via unix cat -v -t. (Is there a way to send you the file so you can see hidden characters? I’ll append the first few lines printed via od -c …/kvpisow2.txt;

text:
u-sit@lsh1001:~$ cat -v -t web/auxlib/web07/InclReq/kvpisow2.txt;
Key US Value United States
Key AF Value Afghanistan
Key AL Value Albania
Key AG Value Algeria

all characters …
0000000 K e y U S V a l u e U n i
0000020 t e d S t a t e s \n K e y
0000040 A F V a l u e A f g h a n i
0000060 s t a n \n K e y A L V a l
0000100 u e A l b a n i a \n K e y
0000120 A G V a l u e A l g e r i a
0000140 \n K e y A N V a l u e A
0000160 n d o r r a \n K e y A O V
0000200 a l u e A n g o l a \n K e y
0000220 A C V a l u e A n t i g u
0000240 a a n d B a r b u d a \n K
0000260 e y A R V a l u e A r g e
0000300 n t i n a \n K e y A S V a
0000320 l u e A u s t r a l i a \n K
0000340 e y A U V a l u e A u s t
0000360 r i a \n K e y A J V a l u
0000400 e A z e r b a i j a n \n K e

usit

Key US Value United States

So if you split this on \s, this gives you an array with only 4 results, right? If there are only 4 results then why are you expecting 5, 6, 7, 8?

Some countries have that many parts; e.g.,

Key MK Value Macedonia, The Former Yugoslav Republic of

Sponsor our Newsletter | Privacy Policy | Terms of Service