Reputation: 231
I have a string e.g. 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?"
Upvotes: 2
Views: 222
Reputation: 977
$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;
Upvotes: 0
Reputation: 1231
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
}
}
?>
Upvotes: 1
Reputation: 26143
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
Upvotes: 1
Reputation: 12433
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;
}
}
Upvotes: 1
Reputation: 890
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;
}
}
Upvotes: 2
Reputation: 59681
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. e.g.
<?php
$str = "1398723242";
$filtered = array_filter(str_split($str), function($v){
return $v & 1;
});
echo implode("", $filtered);
?>
output:
13973
Upvotes: 5