如何在PHP中只将字符串中的数字保存到int数组中

in my POST variable i have: print_r($_POST["partecipanti"]); It displays ["1", "2"]

I want to save only the numbers of the post variable in an int array. I tried

$array = array();
 preg_match_all('/-?\d+(?:\.\d+)?+/', $_POST["partecipanti"], $array);

But print_r($array) returns

Array (
 [0] => Array (
        [0] => 1
        [1] => 2
        )
    )

How can i have a variable like

Array (
  [0] => 1
  [1] => 2
     )

Hope i explained good, thanks all in advance

preg_match_all returns a new multidimensional array every time. But you could just "pop" the array:

$array = array();
preg_match_all('/-?\d+(?:\.\d+)?+/', $_POST["partecipanti"], $array);
$array = $array[0];

Returns:

Array (
  [0] => 1
  [1] => 2
)

to filter integer values from an array, use array_filter

$arr = array_filter($_POST["participanti"], function($v) { return is_int($v); });

In case you want to convert the array values into integers:

$arr = array_map(function($v) { return (int)$v; }, $_POST["participanti"]);

In both cases the $arr contains only integer values.

Assuming $_POST["partecipanti"]) is a string because you use it directly in your example and the second parameter of preg_match_all is a string.

preg_match_all returns an array where the matches are in the first entry and contains array of strings. You could get that array by using $array[0] .

Besides 1 and 2, your regex -?\d+(?:\.\d+)?+ also matches for example -8.44 or 99999999999999999999999999.

If you want an array of int, you could use array_map with for example the function intval for the callback.

Note the maximum size of an int and the rounding of the values.

For example:

$str = "test 1, test 2, test 2.3 and -8.44 plus 99999999999999999999999999999999999999999999999999";
preg_match_all('/-?\d+(?:\.\d+)?/', $str, $array);
$array = array_map/**/("intval", $array[0]);
var_dump($array);

Demo

That results in:

array(5) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(2)
  [3]=>
  int(-8)
  [4]=>
  int(9223372036854775807)
}