0

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.

6
  • What you have try so far? Commented Jun 23, 2016 at 6:45
  • show your code with the problem statement. Commented Jun 23, 2016 at 6:45
  • need to insert only numeric values in table Commented Jun 23, 2016 at 6:46
  • It's array_filter Commented Jun 23, 2016 at 6:46
  • i got string from a table column and need insert into only numeric to another table column Commented Jun 23, 2016 at 6:48

5 Answers 5

4

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

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

1 Comment

just use straight up array_filter(explode(',', $str), 'is_numeric'), no need for that anonymous
2
print_r(array_filter(
    explode(',', '1,36,42,43,45,69,Standard,Executive,Premium'),
    'ctype_digit'
));

Comments

0
<?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

Comments

0

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
)

Comments

0

Tra this:

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

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.