Adding Key/Value pairs from file into associative array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Teddy-O
Forum Newbie
Posts: 1
Joined: Thu Feb 11, 2010 9:58 pm

Adding Key/Value pairs from file into associative array

Post by Teddy-O »

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

Code: Select all

<?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[$ffe[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

Code: Select all

array_key_exists("FirstName", $ffa);
I get a return of

Code: Select all

false
and

Code: Select all

echo $ffa["FirstName"];
returns

Code: Select all

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.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Adding Key/Value pairs from file into associative array

Post by requinix »

Each line in the file looks like

Code: Select all

"Key"=>"Value"
When you use explode(=>) you'll get "Key" as [0] and "Value" as [1] - with the quotes.

Code: Select all

array_key_exists('"FirstName"', $ffa);
To fix that, remove the quotes and (probably) run stripslashes the the stuff inside.

Code: Select all

$ffa[stripslashes(trim($ffe[0], '"'))]=stripslashes(trim($ffe[1],'"'));
Post Reply