1

I have a row of data which contains numbers and splits by '-', sth like this: 2012-421-020-120407 Now I want to generate a parity digit (0 or 1) at the end of this string in my php code. But I have no idea how to do it.

Thanks in advance

Matt Stone
  • 291
  • 2
  • 4
  • 15

1 Answers1

1

If you have your numbers, use % to determine if the number is divisible by 2. If it is, it's even. If it's not, it's odd. Gather your parity from that result.

$numbers = "2012-421-020-120407";
$numbers_array = explode( "-", $numbers );

print_r( $numbers_array ); // [0]=>2012 [1]=>421 [2]=>020 [3]=>120407

foreach ( $numbers_array as &$number )
  $number .= ( $number % 2 == 0 ) ? 0 : 1 ;

print_r( $numbers_array ); // [0]=>20120 [1]=>4211 [2]=>0200 [3]=>1204071

If you would like the parity of the sum of numbers, you can try the following:

$numbers = "2012-421-020-120407";
preg_match_all( "/[0-9]+/", $numbers, $matches );

$parity = array_sum( $matches[0] ) % 2 ;

echo $parity; // Outputs 0 or 1
Sampson
  • 265,109
  • 74
  • 539
  • 565
  • first thanks for your reply, you mean I use these numbers: 2012-421-020-120407? how to use % to determine here? maybe I should first find the sum? I dont know! please make it clean. Thank you – Matt Stone Apr 07 '12 at 07:06
  • @MattStone Are you wanting to find the parity of the sum of all numbers? Or each set of numbers individually? Above, I show you how to accomplish this for each set of numbers resulting in the exploded string. – Sampson Apr 07 '12 at 07:07
  • He say a parity, so I suppose it should be only one that sum them yp – unsym Apr 07 '12 at 07:08
  • I want to find it for sum of them. – Matt Stone Apr 07 '12 at 07:08
  • @MattStone Please see my amended answer above. – Sampson Apr 07 '12 at 07:11
  • Dear Jonathan Sampson this is exactly what i want, Thank you so much :) – Matt Stone Apr 07 '12 at 07:19