I am trying do to this exercise:
"Write a PHP program to exchange the first and last characters in a given string and return the new string."
The thing I’ve tried to do is this:
function stringReverse($str){
$newStr = array($str);
$tab = [];
for($i = 0 ; $i<count($newStr); $i++){
if($newStr[$i] == [0] && $str[$i] == [count($newStr)-1]){
$tab[$i] = count($newStr)-1 && $tab[$i]= $newStr[0];
}
return $tab;
}
}
echo stringReverse("abcd");
but it’s not working – I get this error :
PHP Notice: Array to string conversion in on line 89 Array
I’m expecting this result :
dbca
Goal of exercise : exchange first and last character of a string.
Can anyone help with this?
3
Answers
This might be a simpler way:
Note that this assumes simple, one-byte characters. It won’t work if you have multibyte strings.
It seems like there are a few issues with your code. Let’s go through them and fix them step by step just because you are new it would be a good practice if I correct
your code instead of giving some solutions .
Incorrect array initialization: Instead of using array($str), you can directly assign the string to the $newStr variable.
Incorrect condition and assignment: The condition if ($newStr[$i] == [0] && $str[$i] == [count($newStr)-1]) is incorrect. You are comparing the values with [0] and [count($newStr)-1], which is not valid syntax.
Additionally, the assignment $tab[$i] = count($newStr)-1 && $tab[$i] = $newStr[0]; is incorrect.
Early return: The return $tab; statement is placed inside the for loop, which will cause the loop to terminate after the first iteration. You should move the return statement outside the loop.
Incorrect output format: To return the new string with the first and last characters exchanged, you need to concatenate the characters correctly.
Here’s the corrected code:
Using that a string can be accessed as an array, you could just swap the first and last elements of the array. So store the one value, replace it with the other and then complete the swap…