Question

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

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top