How can I with PHP swap every two digits in a long number value? You can see an example below:
Example: 12345678
Converted to: 21436587
How can I with PHP swap every two digits in a long number value? You can see an example below:
Example: 12345678
Converted to: 21436587
First you have to convert to array.For that use
$array=explode("",$string);
You will get {"1","2","3","4","5","6","7","8"}
Then call the below function.
function swapNumbers($array){
$finalString="";
for($i=0;$i<sizeOf($array);$i++){
if($i!=0){
if($i%2==0){
$finalString.=$array[$i-1].$array[$i];
}
}
if($i==sizeOf($array)-1 && $i%2==1){
$finalString.=$array[$i];
}
}
return $finalString;
}
You will get 21436587
.
You can (for example) solve this by using a loop and substr_replace() function. Take care of odd characters.
As mentioned among the comments, please try with some code first.
<?php
class SwapableNumber
{
private $value;
private $swapSize;
public function __construct($value, $swapSize = 2)
{
$this->value = $value;
$this->swapSize = $swapSize;
}
public function swap()
{
$result = [];
$valueParts = str_split($this->value, $this->swapSize);
foreach ($valueParts as $part) {
// for last part and if it is not complete in size
// (e.g 2 number for a swapSize == 2), it returns
// it unchanged. If the requirement is that partial
// groups of digits should be reversed, too, remove the
// conditional block.
if (strlen($part) < $this->swapSize) {
$result[] = $part;
break;
}
$result[] = strrev($part);
}
return implode('', $result);
}
}
// Example usage (by default the swap size is 2 so it swaps every 2 digits):
$n = new SwapableNumber(12345678);
echo $n->swap();