How to get the middle character from string in PHP

2 Answers

0 votes
$s = "programming";

$index = round(strlen($s) / 2);

echo $s[$index - 1];


/*
run:

a

*/

 



answered Dec 1, 2020 by avibootz
0 votes
$s = "python";
 
$len = strlen($s);
$index = round($len / 2);
 
if ($len % 2 == 1) {
    echo $s[$index - 1];
} else if ($len % 2 == 0) {
    echo $s[$index - 1];
    echo $s[$index];
}
 
 
 
 
/*
run:
 
th
 
*/

 



answered Dec 1, 2020 by avibootz
edited Dec 2, 2020 by avibootz
...