B
B
Buromir2018-04-29 19:48:54
PHP
Buromir, 2018-04-29 19:48:54

How to copy a file line by line into an array so that each new word is a separate element of the array?

I am trying to copy the file to the array in a loop so that each word in the file becomes an element of the array,
the file itself is

test
test
netest

<?php
$flag=0;
$lines = file('file.txt');

foreach ($lines as $line_num => $line) {

  echo $line . "<br />\n";	

  if ($line=='test')

  {
$flag=1;
  }
}

echo $flag;
?>

It displays the information line by line and everything seems to be correct, but the problem is that if the last word in the file is not "test", then the flag variable displays 0 even if the word "test" is present in the file, who can answer why this happens, because everything is displayed in the loop words including "test" and the flag should be equal to 1?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Codebaker, 2018-04-29
@Buromir

Instead of a direct comparison, use one of the following constructs

if (strpos($line, 'test') !== false) { ... } // string contains

if (substr($line, 0, 4 ) === 'test') { ... } // string starts with

D
Dmitry, 2018-04-30
@By_Engine

$str = 'test
test2
test3';
$arr = explode("\n", $str);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question