2

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');

3

4 Answers 4

9

Use str_split

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

Comments

2

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]);

2 Comments

of course, there are lot ways of optimization, i've just shown the way how to access string elements without using specific functions for converting the string to array
i also did not understand the downvote. can you explain (addressing to its author)?
0

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

Comments

-2

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];

2 Comments

An interesting approach but really not recommended.
Will not work: e.g. $val is never used before its assigned to $array1, whereas array1 is (propably accidentally) used twice.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.