How to read two integer variables on the same line with PHP?

Asked

Viewed 67 times

-1

I would like to know how I can assign values, via console, to two variables of the whole type using the same line. I know how to do this in Python and Java but I don’t know in PHP.

Here’s the code I’m testing.

<?php
declare(strict_types=1);

$numero1 = null;
$numero2 = null;

$numero1 = (int)readline("Informe o primeiro e o segundo número inteiro: ");
var_dump($numero1);
var_dump($numero2);
  • 3

    The person will separate by space, comma or what? If you can [Dit] and give an example of what the input is, it helps. I’m trying to locate other posts that talk about it, but basically that’s it, you do it $linha = readline('texto'); without the int, will come a stirng. There does $valores = explode('separador',$linha);, then the values will be in $primeiro = (int) $valores[0], $segundo = (int) $valores[1] ... etc.

2 answers

0

Just use the code below, in the explode you can change the 'separator', in the example is a comma but could be a space for example: explode(' ',$numero);

<?php
declare(strict_types=1);
$numero = null;
$numero1 = null;
$numero2 = null;

$numero = readline("Informe o primeiro e o segundo número inteiro: "); // ex: 1,2
$numero = explode(',',$numero);

$numero1 = (int)$numero[0];
$numero2 = (int)$numero[1];

var_dump($numero1);
var_dump($numero2);

-1

It is possible to extract from an input string an array of strings composed only integers independent of specifying some separator.
For this just split the input string to each character that is not a decimal digit with preg_match_all.

The function preg_match_all() captures the matches of a pattern regular expression in a string.
One can instruct the preg_match_all() that captures only the integer numbers of the string with the pattern
/[-+]?\d+/.
The flag PREG_SET_ORDER sorts the results so that the first value of the capture matrix is the first matching set, the second value of the capture matrix is the matching set and so on.

With the function array_map() apply the conversion function to integers intval() each element of the array previously returned by preg_match_all() flattened by the function array_merge() .

With list() assign an array to multiple variables.

<?php

$entrada = readline("Informe o primeiro e o segundo número inteiro: "); 

preg_match_all('/[-+]?\d+/', $entrada, $numeros, PREG_SET_ORDER);

list($numero1, $numero2) = array_map('intval', array_merge(...$numeros));


var_dump($numero1);
var_dump($numero2);

Test the example on Repl.it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.