How to read integers separated by space from file in php

I am trying to read a line where several numbers are separated by space using php. I originally tried to use fscanf, but the problem is that fscanf reads one line at a time, it only reads the first number. I am confused what to do.

Input example 20 30 -5987 456 523

+4
source share
3 answers

The best approach for this is to use a combination of tearing and reading files. Initially, the strategy is read as a whole line as a line. Then use explode to store the entire number in the array. However, in this case, the array will be a string array later, we can change the type of the 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);
?>
+7
source
$input = trim(fgets(STDIN));
$arr = explode(" ", $input);      
foreach($arr as &$number){
    $number = (int)$number;
}
0

"fopen", "" . :

echo "Please enter series limit : ";
$handles = fopen ("php://stdin","r");
$n = trim(fgets($handles));

, , .

0

All Articles