Dong3000
Dong3000

Reputation: 596

Converting several array values to integer

As shown in String to array of Integers php, there is a solution to convert ALL array elements to integer. But what if my array looks like this:

$v=array(0.00, "0.00", "test", 50);

I need a converted array where all numeric elements (even if quoted, like "0.00") are converted to integer, but strings (like "test") must remain strings...

Upvotes: 1

Views: 78

Answers (1)

Sougata Bose
Sougata Bose

Reputation: 31749

Try with array_map. It will convert all the elements(except the strings you mentioned) to integer.

function convert_data($data) {
    if (is_numeric($data)) {
        $data = (int) $data;
    }
    return $data;
}
$ints[] = array_map('convert_data', $v);
var_dump($ints);

Upvotes: 1

Related Questions