Search code examples
phparrayssplitline-count

PHP split up to every nth line into an array


I am attempting to split a log file by up to every nth line instead of every line. Currently I am using preg_split for line breaks which gives me a new array element for each line. I am trying to split by nth line.

$str = file_get_contents('filename');
$arr1 = preg_split("/\r\n|\n|\r/", $str, -1, PREG_SPLIT_NO_EMPTY);    

Solution

  • You could alternatively try something like this?

    $chunks = array_chunk( file( $filename ), 5 );