l2aelba
l2aelba

Reputation: 22217

Get arrays from a file then loop it

Try to get arrays from a file like...

data.txt

Array
(
    [0] => 288
    [1] => 287
    [2] => 173
)

my.php

$data = file('data.txt');

foreach ($data as $id) {
    echo $id." - ";
}

Why its echo all arrays back ? like data.txt

Why not echo like 288 - 287 - 173 ?

CLOSED : I using JSON now

Upvotes: 1

Views: 83

Answers (2)

user1726343
user1726343

Reputation:

When saving your data, get the string representation using serialize:

$str = serialize($arr);

You can then use unserialize to decode your array:

$arr = unserialize(file(data.txt));

Upvotes: 3

Martin Sommervold
Martin Sommervold

Reputation: 152

Your method loads the data in data.txt as a string, and php will not parse it as code. Try

$data = eval(file(data.txt));

See more on eval here: PHP manual on eval

Also note that the syntax in data.txt is invalid. You want:

array(288, 287, 173);

PHP will automatically create the indexes as needed.

On a second note, this is probably not the best way to go about it. Not knowing what you aim to achieve here, but would it not be better to just have the array set in your php file?

Upvotes: 2

Related Questions