Jump to content

Reading an array


marklarah

Recommended Posts

Hi

 

Let's say I have just declared an array as such:

<?php
$array = array( "Cheese" => "$4.99", "Pepperoni" => "$6.99", "Mushroom" => "$5.49", "Pineapple" => "$5.99" );

print_r($array);
?>

 

Will obviously result in

Array

(

    [Cheese] => $4.99

    [Pepperoni] => $6.99

    [Mushroom] => $5.49

    [Pineapple] => $5.99

)

 

But let's say I had { Cheese" => "$4.99", "Pepperoni" => "$6.99", "Mushroom" => "$5.49", "Pineapple" => "$5.99" } stored in a text file. Short of doing a load explodes, is there any way to convert that to an array? I'm thinking maybe something with eval() but I've no idea yeah.

 

8)

Link to comment
https://forums.phpfreaks.com/topic/190394-reading-an-array/
Share on other sites

there is the nastyness of eval();

 

if you are storing this string in a text file then perhaps consider using json_encode and json_decode to help you out.

 

Actually the text file I'm looking at which I want to do this with looks like it's already had that done to. So I'll use the reverse to get something like what I have above...then

 

*just tried it*

 

You are a god.

 

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/190394-reading-an-array/#findComment-1004362
Share on other sites

save it in the text file like this:

 

a:4:{s:6:"Cheese";s:5:"$4.99";s:9:"Pepperoni";s:5:"$6.99";s:8:"Mushroom";s:5:"$5.49";s:9:"Pineapple";s:5:"$5.99";}

 

then when you read it do this:

 

$file = 'array.txt';
$handle = fread($file, 'r');
$arr = fread($handle, filesize($file));
fclose($handle);

print_r(unserialize($arr));

 

check serialize, unserialize in the manual for more info

Link to comment
https://forums.phpfreaks.com/topic/190394-reading-an-array/#findComment-1004363
Share on other sites

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.