Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read integers separated by space from a file in php

Tags:

php

I am trying to read a line where multiple numbers were separated by space using php. Initially I tried using fscanf however the issue is, as fscanf read one line at a time, it only reads the first number. I am confused what to do.

Sample Input 20 30 -5987 456 523

like image 870
Muhammad Raihan Muhaimin Avatar asked Feb 16 '23 01:02

Muhammad Raihan Muhaimin


1 Answers

The best approach for this case is to use a combination of explode and file reading. The strategy is initially read the whole line as an string. Then use explode to store the all the number in an array. However in that case the array would a string array later on we can change the type of array element from String to integer. Here is how

<?php
$_fp = fopen("php://stdin", "r");
fscanf($_fp, "%d\n", $count);
$numbers = explode(" ", trim(fgets($_fp)));
foreach ($numbers as &$number)
{
    $number = intval($number);
}
sort($numbers);
?>
like image 173
Muhammad Raihan Muhaimin Avatar answered Mar 03 '23 16:03

Muhammad Raihan Muhaimin