Reputation: 1544
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
Reputation: 843
Tra this:
$string = "1,36,42,43,45,69,Standard,Executive,Premium";
print_r(array_filter(explode(',', $string), 'is_numeric'));
Upvotes: 0
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
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
Reputation: 54831
print_r(array_filter(
explode(',', '1,36,42,43,45,69,Standard,Executive,Premium'),
'ctype_digit'
));
Upvotes: 2
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