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 165 views
2 answers 167 views
3 answers 228 views
1 answer 159 views
1 answer 141 views
1 answer 263 views
1 answer 183 views
...