Good day,

There is a text file with the following contents:

ключ1|значение1 ключ2|значение2 ключ777|значение777 

How can I create an array, placing in the first element of the array $arr['key']['value'] respectively, ключ1 and значение1 , and so with all the elements?

Thank.

  • [Associative array] [1] [1]: php.su/learnphp/datatypes/?array#assoc - NMD
  • traditionally: why the question is made out by the code? - etki
  • @ Roman Rakzin, If you are given an exhaustive answer, mark it as correct (click on the check mark next to the selected answer). - Mr_Epic

4 answers 4

  $content = file_get_contents('application/Data/file1.txt'); $Data = explode("\n", $content); $x=0; foreach($Data as $value) { $Stroka= explode('|',$value); $arr[$x] =array('Key'=>$Stroka[0],'Value'=>$Stroka[1],'File'=>'Файл'); $x++; } print_r($arr); 
     $text = file_get_contents('file.txt'); $str = explode("\n", $text ); $array = array(); foreach($str as $val){ $str_t= explode('|',$val); $array[$str_t[0]] = $str_t[1]; } print_r($array); 

      PR function fgetcsv() - reads from the file a string of values ​​through a separator:

       $result = array(); if (( $handle = fopen( "hashcode.txt", "r")) !== FALSE) { while (( $data = fgetcsv( $handle, 1000, "|")) !== FALSE) { if( count( $data) != 2) continue; // нам нужно ровно два элемента $result[ $data[0]] = $data[1]; } fclose( $handle); }; 

        $f = file('file.txt'); for ($i=0;$i<count($f);$i++){ $s = explode('|',$f[$i]); $ar[$s[0]] = $s[1]; }

        in $ ar - will be your array

        • * what if the file is 1GB and the RAM on the hosting is 192MB? * What if there is no separator in the string? - Sergiks