Can you provide details as to what is wrong with it or how it could be done better?
Starting the counter length doesn't consider multi-byte characters
As was mentioned in a comment, the first expression of the for
loop contains a call to strlen($str)
to calculate the first value of $i
. Per the documentation of strlen()
:
Note:
strlen()
returns the number of bytes rather than the number of characters in a string.
For multi-byte strings this will not work well as some characters may be broken up. One could use mb_strlen()
to get the length of a multi-byte string and mb_substr()
to get multi-byte characters at given indexes.
Use idiomatic spacing
While this is purely subjective, most idiomatic PHP follows standards like PSR-12, which has many recommendations on styling and other code conventions. The line which stands out as the most incongruent with such conventions is the loop declaration:
for($i=strlen($str)-1;$i>=0;$i--){
Idiomatic PHP code would have more spaces after the keyword for
, the semi-colons and the closing parenthesis, as well as surrounding binary operators:
for ($i = strlen($str)-1; $i>=0; $i--) {
The php.net documentation often has idiomatic code. For example, the documentation for the for
keyword contains this example (one of four):
<?php /* example 1 */ for ($i = 1; $i <= 10; $i++) { echo $i; } ...
Appending strings can be done with .=
This may or may not be what the evaluators were looking for- one could append the strings using double quoted strings with variable parsing.
Iteration style can be simpler with foreach
One could split the string using a function like preg_split()
and then iterate over the characters using foreach
. This allows for the elimination of the iterator variable.
$characters = preg_split('//u', $str);
foreach ($characters as $character) {
$reversed = "{$character}{$reversed}";
}