McJohnson McJohnson - 2 months ago 16
PHP Question

Merging arrays in while() in PHP

I found the need to use element keys as identifiers and therefore stumbled upon the following predicament.

I am reading a file and parsing it in order to extract the filenames and then work with them. As I am looping through all the lines in the file, I am creating a new array for every match to the regular expression:

$file = fopen('/home/user/log.txt', 'r');

if ($file) {
while (($line = fgets($file)) !== false) {
if (preg_match('~^/[^:]+~m', $line, $files)) { //match everything until the first ':' to get file names
var_dump($files);
}
}
}


Thus, I get:

array (size=1)
0 => string '/home/user/whatever.php' (length=23)
array (size=1)
0 => string '/home/user/run.php' (length=18)
array (size=1)
0 => string '/home/user/sth.php' (length=18)


I would like to merge them all into one single array so that they may have different keys. Can that be achieved in this scenario or should I consired rewriting the loops?

Answer

Do something like this instead to add them to an array as you loop:

$file = fopen('/home/user/log.txt', 'r');
$array = [];

if ($file) {
  while (($line = fgets($file)) !== false) 
  {
     if (preg_match('~^/[^:]+~m', $line, $files)) 
     { //match everything until the first ':' to get file names
         array_push($array, $files);
     }
  }
}

var_dump($array);
Comments