Reading and writing arrays in PHP?

I am currently trying to use PHP to track the number of “likes” on the pages of my site. What I would like to do is put all the information in one array, not a separate file for each page, each of which contains one integer. What I was trying to do was set up a file (name it data.txt) that contains this array.

$array = array(
    "Page1" => 10,
    "Page2" => 3,
);

For example, above, page 1 has 10, while page2 - 3. This is the real meat of the matter: . How can I write the above array to a text file and then read it later? Most of the approaches I tried end up simply reading a string that is not what I'm looking for (I want to be able to easily access the number of likes directly to the array).

Here var_dumpfor everyone who was interested:

array(2) { ["Page1"]=> int(10) ["Page2"]=> int(3) }

Maybe there is a way to parse this array?

+4
source share
1 answer

As Mark Baker suggested, you need to serialize the data to save it in a file. You can read it later and deserialize it back to an array. Here's how:

<?php

// DISPLAY ARRAY BEFORE SAVING IT.    
$old_array = array( "Page1" => 10,
                    "Page2" => 3,
                  );
echo "OLD ARRAY" .
     "<br/><br/>";
print_r( $old_array );

// WRITE ARRAY TO FILE.
$old_data = serialize( $old_array );
file_put_contents( "my_file.txt",$old_data );

// READ ARRAY FROM FILE.    
$new_data = file_get_contents( "my_file.txt" );
$new_array = unserialize( $new_data );

// DISPLAY ARRAY TO CHECK IF IT OK.
echo "<br/><br/>" .
     "NEW ARRAY" .
     "<br/><br/>";
print_r( $new_array );

?>

This is what you should see on the screen:

OLD ARRAY

Array ( [Page1] => 10 [Page2] => 3 )

NEW ARRAY

Array ( [Page1] => 10 [Page2] => 3 ) 

And if you open "my_file.txt", you will see the following:

a:2:{s:5:"Page1";i:10;s:5:"Page2";i:3;}
+3
source

All Articles