How can I create an associative array from a file in PHP?
To create an associative array from a file in PHP, you can read the file line by line and parse each line to extract key-value pairs. Then, store these pairs in an associative array where the keys are the keys extracted from the file and the values are the corresponding values. Finally, you can use this associative array for further processing or manipulation.
<?php
// Open the file for reading
$file = fopen('data.txt', 'r');
// Initialize an empty associative array
$assocArray = array();
// Read the file line by line
while (!feof($file)) {
$line = fgets($file);
// Parse the line to extract key-value pairs
$data = explode(':', $line);
// Store the key-value pair in the associative array
$assocArray[$data[0]] = trim($data[1]);
}
// Close the file
fclose($file);
// Print the associative array
print_r($assocArray);
?>
Related questions
-
PHP MySQL data integrity
-
PHP mysql_query socket parameter
-
SQL syntax error MySQL server version WHERE clause