SAUMYA
SAUMYA

Reputation: 1544

Comma delimited string into an array but only numeric values in PHP?

There is an string like

1,36,42,43,45,69,Standard,Executive,Premium

I want to convert it in array but need only numeric values as

Array
(
   [0] => 1
   [1] => 36
   [2] => 42
   [3] => 43
   [4] => 45
   [5] => 69
)

Not all string value in array.

Upvotes: 0

Views: 111

Answers (5)

Raghav Patel
Raghav Patel

Reputation: 843

Tra this:

$string = "1,36,42,43,45,69,Standard,Executive,Premium";
print_r(array_filter(explode(',', $string), 'is_numeric'));

Upvotes: 0

Divyesh Patoriya
Divyesh Patoriya

Reputation: 518

Have a look attached snippet:

Please have a look Demo : https://eval.in/593963

<?php
$c="1,36,42,43,45,69,Standard,Executive,Premium";
$arr=explode(",",$c);

foreach ($arr as $key => $value) {
    echo $value;
    if (!is_numeric($value)) { 
        unset($arr[$key]);
    }
}
print_r($arr);

?>

Output:

 Array
 (
    [0] => 1
    [1] => 36
    [2] => 42
    [3] => 43
    [4] => 45
    [5] => 69
    [6] => Standard
    [7] => Executive
    [8] => Premium
)
Array
(
    [0] => 1
    [1] => 36
    [2] => 42
    [3] => 43
    [4] => 45
    [5] => 69
)

Upvotes: 0

antoni
antoni

Reputation: 5546

<?php
$array = array('1','36','42','43','45','69','Standard','Executive','Premium');
foreach($array as $value) if (is_integer($value)) $new_array[] = $value;

print_r($new_array);
?>

[EDIT] oh yeah I actually prefer your version RomanPerekhrest & u_mulder :p

Upvotes: 0

u_mulder
u_mulder

Reputation: 54831

print_r(array_filter(
    explode(',', '1,36,42,43,45,69,Standard,Executive,Premium'),
    'ctype_digit'
));

Upvotes: 2

RomanPerekhrest
RomanPerekhrest

Reputation: 92874

Simple and short solution using array_filter, explode and is_numeric functions:

$str = "1,36,42,43,45,69,Standard,Executive,Premium";
$numbers = array_filter(explode(",", $str), "is_numeric");

print_r($numbers);

The output:

Array
(
    [0] => 1
    [1] => 36
    [2] => 42
    [3] => 43
    [4] => 45
    [5] => 69
)

http://php.net/manual/en/function.is-numeric.php

Upvotes: 4

Related Questions