How to swap every two characters (pairs) in a string with PHP

1 Answer

0 votes
function swap($s, $index1, $index2) {
    $tmp = $s[$index1];
    $s[$index1] = $s[$index2];
    $s[$index2] = $tmp;
    
    return $s;
} 


$s = "abcdef"; 
 
for ($i = 0; $i < strlen($s); $i++) {
     if ($i % 2 === 0) {
         if (($i + 1) < strlen($s)) {
             $s = swap($s, $i, $i + 1);
         }
     }
}
     
echo $s;



  
/*
run:
       
badcfe

*/

 



answered Jun 21, 2019 by avibootz

Related questions

...