Jump to content

Adding Key/Value pairs from file into associative array


Teddy-O

Recommended Posts

I hope this is a newbie problem.

 

I've got a text file with a list of Key/Value pairs extracted from an HTML form on my hosted web server. I send this file as an email attachement to my local computer and am running a script that puts these values into an an associative array. Later in the script I access the values one at a time in the array and send them to my local database (using prepared statements with bound parameters and a MySQL database).

 

The Key/Value pairs in the email-attached file look like this:

 

"FirstName"=>"Mary"

"LastName"=>"Lamb"

"Address"=>"Some Street"

...and so forth...

 

Here is the script I wrote to put these values into an associative array

 

<?php
$ff = file('list.txt');  // list.txt is the file attached to the email; ff=form fields
foreach($ff as $key=>$value) {
    $ffe = explode("=>", $value);  // ffe=form fields exploded
    $ffa[$mfe[0]]=$ffe[1];  // ffa=form fields associative array
}
?>

 

When I use iterative commands, like print_r, foreach($ff as $key=>$value), and array_keys, I can see that the associative array is constructed correctly, but when I use non-iterative commands like

array_key_exists("FirstName", $ffa);

I get a return of

false

and

echo $ffa["FirstName"];

returns

null

.

 

Is this a known aspect of the language or am I missing something?

 

BTW, I am successfully using parse_str() to create an associative array that does allow non-iterative access to the Key/Value pairs (after reformatting the file attached to the email). Still, I am curious about this discrepancy in the associative array's readability.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.