Search code examples
phpswapdigits

Swap every two digits


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


Solution

  • 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.