简体   繁体   中英

How to convert a string of numbers into an array?

I have a string eg 1398723242 . I am trying to check this string and get the odd numbers out which in this case is 13973 .

I am facing problem on how to put this string into an array. After putting the string into an array I know that I have to loop through the array, something like this:

foreach($array as $value){
    if($value % 2 !== 0){
        echo $value;
    }
}

So can any body please help on the first part on "How to put the above string into an array so I can evaluate each digit in the above loop?"

This should work for you:

Just use str_split() to split your string into an array. Then you can use array_filter() to filter the even numbers out. eg

<?php

    $str = "1398723242";
    $filtered = array_filter(str_split($str), function($v){
        return $v & 1;
    });
    echo implode("", $filtered);

?>

output:

13973

Array map is your function (mixed with split )

$array  = array_map('intval', str_split($number));
foreach($array as $value){
    if($value % 2 !== 0){
        echo $value;
    }
}

Use str_split() http://www.php.net/manual/en/function.str-split.php

$string = "1398723242";
$array = str_split($string);
foreach($array as $value){
    if($value % 2 !== 0){
        echo $value;
    }
}

You have to know if the string is an array of chars. so you can just iterate it :

<?php
$string = "1398723242";
for($i=0; $i < strlen($string); ++$i){
    if($string[$i]=='....'){
       $string[$i] = ''; // Just replace the index like this
    }  
}
?>

if you want string as result, don't convert to array

$str = "1398723242";
echo preg_replace('/0|2|4|6|8/','', $str); //13973

Or, more faster

echo str_replace(array(0,2,4,6,8),'', $str); //13973
$str    =   '1398723242';

$strlen = strlen($str);// Get length of thr string
$newstr;
for($i=0;$i<$strlen;$i++){ // apply loop to get individual character
    if($str[$i]%2==1){ // check for odd numbers and get into a string
        $newstr .=  $str[$i]; 
    }
}
echo $newstr;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM