Home > Backend Development > PHP Tutorial > How to Store and Retrieve Arrays in PHP Using JSON Serialization?

How to Store and Retrieve Arrays in PHP Using JSON Serialization?

Mary-Kate Olsen
Release: 2024-10-19 06:58:30
Original
211 people have browsed it

How to Store and Retrieve Arrays in PHP Using JSON Serialization?

Storing and Retrieving Arrays in PHP

To store an array for later retrieval with PHP, you have multiple options. One efficient and flexible approach is through JSON serialization. Here's how to do it:

Storing an Array (store_array)

  1. Convert the array to a JSON string using json_encode() function.
  2. Save the JSON string to a file using file_put_contents().

Example:

<code class="php">$arr1 = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];
file_put_contents("array.json", json_encode($arr1));</code>
Copy after login

Retrieving an Array (restore_array)

  1. Load the JSON string from the file using file_get_contents() function.
  2. Convert the JSON string back to an array using json_decode() function.

Example:

<code class="php">$arr2 = json_decode(file_get_contents('array.json'), true);</code>
Copy after login

The json_encode() and json_decode() functions provide efficient and human-readable serialization of arrays, making it easy to store and retrieve arrays as needed.

The above is the detailed content of How to Store and Retrieve Arrays in PHP Using JSON Serialization?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template