Home > Mobile >  PHP Array split string and Integers
PHP Array split string and Integers

Time:05-13

I want below code to be string as one array and numbers as another array. How could we do that?

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

CodePudding user response:

You could also do this in one line using 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);

CodePudding user response:

Loop through them, check if is_numeric and add to appropriate array:

$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

CodePudding user response:

    $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);
        }
    } 

CodePudding user response:

Using a foreach() like in @jnko's answer will be most performant because it only iterates over the array one time.

However, if you are not concerned with micro-optimization and prefer to write concise or functional-style code, then I recommend using array_filter() with is_numeric() calls, then making key comparisons between the first result and the original array.

Code: (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));

Output:

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',
)
  • Related