PHP 数组拆分字符串和整数

PHP Array split string and Integers

下面是一组字符串和数字。如何将字符串和数字值拆分为单独的数组(字符串在一个数组中,数字在另一个数组中)?

array('a','b','c',1,2,3,4,5,'t','x','w')

遍历它们,检查是否 is_numeric 并添加到适当的数组:

$original = array('a','b','c',1,2,3,4,5,'t','x','w');

$letters = array();
$numbers = array();

foreach($original as $element){
    if(is_numeric($element)){
        $numbers[] = $element;
    }else{
        $letters[] = $element;
    }
}

https://3v4l.org/CAvVp

    $data = array('a','b','c',1,2,3,4,5,'t','x','w');
    $integerArray = array();
    $stringArray = array();
    $undefinedArray = array();
    foreach($data as $temp)
    {
        if(gettype($temp) == "integer")
        {
            array_push($integerArray,$temp);
        }elseif(gettype($temp) == "string"){
            array_push($stringArray,$temp);
        }else{
            array_push($undefinedArray,$temp);
        }
    } 

您也可以使用 array_filter()

在一行中完成此操作
$numbers = array_filter($arr,function($e){return is_numeric($e);});
$alphas = array_filter($arr,function($e){return !is_numeric($e);});

print_r($numbers);
print_r($alphas);

使用@jnko 的回答中的foreach() 将是最有效的,因为它只遍历数组一次。

但是,如果您不关心 micro-optimization 并且更喜欢编写简洁或 functional-style 代码,那么我建议使用 array_filter()is_numeric() 调用,然后进行第一个结果和原始数组之间的关键比较。

代码:(Demo)

$array = ['a','b',0,'c',1,2,'ee',3,4,5,'t','x','w'];
$numbers = array_filter($array, 'is_numeric');
var_export($numbers);
var_export(array_diff_key($array, $numbers));

输出:

array (
  2 => 0,
  4 => 1,
  5 => 2,
  7 => 3,
  8 => 4,
  9 => 5,
)
array (
  0 => 'a',
  1 => 'b',
  3 => 'c',
  6 => 'ee',
  10 => 't',
  11 => 'x',
  12 => 'w',
)