-4

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

user1273409
  • 39
  • 3
  • 9
  • 3
    PHP is a programming language. Unless you use a number big enough to not suit variable size in PHP, yeah its pretty much possible. Was that your questions or you want to know how to achieve it? – DJ' Aug 13 '15 at 07:41
  • You should also specify what you want to do if the number has an _odd_ digit count. – paxdiablo Aug 13 '15 at 07:43
  • I want to know how to achieve it. – user1273409 Aug 13 '15 at 07:48
  • 2
    give it a try, post some code and we'll help you from there. SO isnt a coding service. – DevDonkey Aug 13 '15 at 07:52
  • No idea why this question is closed. It's a perfectly valid question, specific, and easy to understand. It should be reopened so I can post this elegant answer as an actual answer, which is this: function swap($n){return ((mb_strlen($n) < 1) ? '' : (isset($n[1]) ? ($n[1] . $n[0] . swap(substr($n, 2))) : $n[0]));} Beware this answer is recursive, so if you cut and paste it wrong, or modify it incorrectly, you run the risk of freezing your server in an infinite loop, as is the risk with all incorrectly written recursive functions. –  Oct 02 '19 at 18:10

3 Answers3

1

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.

Arun Shankar
  • 612
  • 1
  • 5
  • 16
0

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.

Cr_U
  • 37
  • 6
0
<?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();
m1lt0n
  • 361
  • 3
  • 9