How to swap characters in string by index in PHP

3 Answers

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


$s = "abcdef"; 
 
$s = swap($s, 0, 5);
     
echo $s;



  
/*
run:
       
badcfe

*/

 



answered Jun 21, 2019 by avibootz
0 votes
$s = "abcdef"; 
 
$tmp = $s[0];
$s[0] = $s[5];
$s[5] = $tmp;
     
echo $s;



  
/*
run:
       
badcfe

*/

 



answered Jun 21, 2019 by avibootz
0 votes
function swap(&$s, $index1, $index2) {
    $tmp = $s[$index1];
    $s[$index1] = $s[$index2];
    $s[$index2] = $tmp;
} 
 
 
$s = "abcdef"; 
  
swap($s, 0, 5);
      
echo $s;
 
 
 
   
/*
run:
        
fbcdea
 
*/

 



answered Jun 21, 2019 by avibootz

Related questions

2 answers 275 views
2 answers 284 views
3 answers 346 views
1 answer 260 views
1 answer 228 views
1 answer 356 views
1 answer 280 views
...