Search code examples
phparraystextfopenfile-get-contents

Utilize array data saved in TXT file ( PHP)


I am trying to utilize the data saved to list.txt via form submit and display it randomly on page.

index.php

<?php
    //$list = file_get_contents('list.txt'); //Tested without fopen

    $myfile = fopen('list.txt', "r") or die ("");

    $list = fread($myfile,filesize('list.txt'));

    $bg0 = array($list ,'yellow'); // array of colors

    fclose($myfile);

    $i = rand(0, count($bg0)-1); // generate random number size of the array
    $selectedColor = "$bg0[$i]"; // set variable equal to which random color was chosen

    echo selectedColor;
?>

list.txt

'red', 'blue', 'green'

Solution

  • I am not fully sure what you are trying to achieve here, but you have few problems:

    1) selectedColor

    should be $selectedColor

    2) loading of the "array".

    You cannot simply load a text and expect php to guess the format. If you want to load the file and treat it as an array you need to instruct php to do so.

    In your example you can for example split the text and trim unwanted chars:

      $list = explode(',', $list);
      array_walk($list, function(&$elem) {
        $elem = trim($elem, ' \'');
      });
    

    3) $selectedColor = $bg0[$i];

    Replace:

    $selectedColor = "$bg0[$i]";
    

    with:

    $selectedColor = $bg0[$i];
    

    4) array push

    This line is incorrect:

    $bg0 = array($list ,'yellow'); // array of colors
    

    Replace it with:

    $bg0 = array_merge($list, ['yellow']); // array of colors
    

    If you want to operate on a single array you can use array_push but then be sure to change the variable which you use later.

    So for example:

    <?php
    
      //$list = file_get_contents('list.txt'); //Tested without fopen
    
      $myfile = fopen('list.txt', "r") or die ("");
    
      $list = fread($myfile,filesize('list.txt'));
    
      $list = explode(',', $list);
      array_walk($list, function(&$elem) {
        $elem = trim($elem, ' \'');
      });
    
      $bg0 = array_merge($list , ['yellow']); // array of colors
    
      fclose($myfile);
    
      $i = rand(0, count($bg0)-1); // generate random number size of the array
      $selectedColor = $bg0[$i]; // set variable equal to which random color was chosen
    
      echo $selectedColor;
      ?>