Wednesday 5 September 2018

PHP Array does not return correctly

Following code:

$names = file_get_contents('names.txt');
var_dump($names);

Is returning in var_dump:
array (size=1)
  0 => string 'asd
dwqd
asfa
fewfw' (length=22)

Meanwhile, this returns correct way:
$test = array('tete','asdasd','yryr');
var_dump($test);

Result:
array (size=3)
  0 => string 'tete' (length=4)
  1 => string 'asdasd' (length=6)
  2 => string 'yryr' (length=4)

So, the code block when I try to get names from file and make an array of them return an wrong format array. names.txt is built as following:
asd
dwqd
asfa
fewfw


Your problem is you're not splitting the lines into an array, it's just reading the whole files as a block of text.
Use file() with the FILE_IGNORE_NEW_LINES flag. The flag says Do not add newline at the end of each array element, turning your multiple lines into single lines of an array.
Try:
$names = file('names.txt', FILE_IGNORE_NEW_LINES);
var_dump($names);

0 comments:

Post a Comment