简体   繁体   中英

How can I sort values from an existing array by data type?

I try to determine the data type of each array value from an existing array using foreach() and var_dump().

Let's say I have this array: example:

$arr = ['this','is', 1, 'array', 'for', 1, 'example'];

Now I have to take each value of this field and determine its data type.

I try this:

$str = array();
$int = array();

foreach($arr as $k => $val) {
     if(var_dump($arr[$k]) == 'string'){
        $str[] = $arr[$k];
     } else {
        $int[] = $arr[$k];
     }
}

In other words, I try to sort the values from an existing array by data type and create a new array with only 'string' values and a second new array with only 'int' values. But it seems that my 'if' condition isn't working properly. How else could I solve this please? Thank you.

You need to use gettype to get the type of a value, not var_dump :

foreach($arr as $k => $val) {
     if(gettype($arr[$k]) == 'string'){
        $str[] = $arr[$k];
     } else {
        $int[] = $arr[$k];
     }
}

Output:

Array
(
    [0] => this
    [1] => is
    [2] => array
    [3] => for
    [4] => example
)
Array
(
    [0] => 1
    [1] => 1
)

Demo on 3v4l.org

Use gettype

$data = array('this','is', 1, 'array', 'for', 1, 'example');

foreach ($data as $value) {
    echo gettype($value), "\n";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM