I want to use a text file to store my variables and values. How can I put the $var[0] into the respected variable name so i can:

<?php
echo $name;
echo $age;
echo $location;
echo $hobby;
?>

Here's my text format:

variables.txt

name##my name here
age##my age here
location##my city here
hobby##my hobby here

Here's the code.

<?php
  $fh = fopen('variables.txt', 'r');
  $data = fread($fh, filesize('variables.txt'));
  fclose($fh);

  $variables = explode("\n", $data);

  #print_r($variables);

  foreach ($variables as $variable) {
      $var = explode("##", $variable);
      echo $var[0] . " - " . $var[1];
  }
?>

    That way is bad IMO. Theres no reason for you to invent your own fileformat to store variables. For example you can save your variables in an array and use serialize and unserialize to read them:

    // set and write data for example
    $store = array(
    			'name' => 'John',
    			'age' => 29,
    			'location' => 'Finland',
    			'hobby' => 'music'
    		);
    
    $fp = fopen('info.txt','w');
    
    fwrite($fp,serialize($store));
    
    
    // Reading the data
    $infotxt = file_get_contents('info.txt');
    $info = unserialize($infotxt);
    
    
    // Now you can access those normally like arrays:
    echo $info['name'];
    echo $info['age'];
    echo $info['location'];
    echo $info['hobby'];
    
    // Or if you want those to be variables you can use extract function
    extract($info);
    
    echo $name;
    echo $age;
    ...
    

    If you still want to stick with your own fileformat, you have to use variable variables.

      Thanks cahva. Serializing and using the extract function definitely did the work.

        Write a Reply...