How can PHP arrays or JSON be utilized to store and retrieve user data more efficiently than reading from a text file line by line?
Using PHP arrays or JSON can be more efficient than reading from a text file line by line because arrays and JSON provide a structured way to store and retrieve data quickly. With arrays, you can easily access specific elements using keys, while JSON allows you to encode and decode data in a format that is easy to work with. This can lead to faster data retrieval and manipulation compared to parsing text files line by line.
// Storing user data in an array
$userData = [
'username' => 'john_doe',
'email' => 'john.doe@example.com',
'age' => 30
];
// Converting the array to JSON and storing it in a file
$jsonData = json_encode($userData);
file_put_contents('user_data.json', $jsonData);
// Retrieving user data from the JSON file
$jsonData = file_get_contents('user_data.json');
$userData = json_decode($jsonData, true);
// Accessing specific user data
echo 'Username: ' . $userData['username'] . PHP_EOL;
echo 'Email: ' . $userData['email'] . PHP_EOL;
echo 'Age: ' . $userData['age'] . PHP_EOL;