0

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, 'gettype' I missed. My problem solved. @Nick
1

Use gettype

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.