开发者

Split string to array

I am trying to get remainder value using php:

Example:
$string1 ="1477014108152000180343081299001";
$string2 ="1731731731731731731731731731731";  

Each digit of $string1 is multiplied by each digit of $string2

$string1 = 1 4 7 7 0 1 4 1 0 8 1 5 2 0 0 0 1 8 0 3 4 3 0 8 1 2 9 9 0 0 1
           * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
$string2=  1 7 3 1 7 3 1 7 3 1开发者_开发百科 7 3 1 7 3 1 7 3 1 7 3 1 7 3 1 7 3 1 7 3 1

Starting from the front of the string Sum=1 + 28 + 21 + 7 + 0 + 3 + 4 + 7 + 0 + 8 + 7 + 15 + 2 + 0 +0 + 0 + 7 + 24 + 0 + 21 + 12 + 3 + 0 + 24 + 1 + 14 +27 +9 + 0 + 0 + 1 = 246

Remainder = 246 % 10= 6

I want to create array of $string1 and $string2, so that I can easily multiply each value. Please help me to split $string1 and $string2 in to array.

I want array as below:

$array=array('1','7','3','1','7','3','1','7','3','1','7','3','1','7','3','1','7','3','1','7','3','1','7','3','1','7','3','1','7','3','1');


Use str_split


you can access to string characters as to array elements:

for ($i=0, $c=strlen($string1); $i<$c; $i++) 
  echo("char number $i is ". $string1[$i]);


As far as I understand, what you are going to achieve, there is no reason to split the strings, before processing

$size = strlen($string1);
$sum = 0; 
for ($i=0; $i<$size; $i++)
  $sum += $string1[$i] * $string2[$i];

or (only looking at the remainder)

$size = strlen($string1);
$remainder = 0;
for ($i=0; $i<$size; $i++)
  $remainder = ($remaider + $string1[$i] * $string2[$i]) % 10;

The last one is definitly prefered, because you can assume, that the sum will grow very large


You can do this using preg_match_all:

$string1 ="1477014108152000180343081299001";
$string2 ="1731731731731731731731731731731";  

$val = array();
$count = preg_match_all('/\d/', $string1, &$val);
$array1 = $val[0];

$val = array();
$count = preg_match_all('/\d/', $string2, &$val);
$array1 = $val[0];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜