Need to hep to change multiple characters in a string using some loop without built-in functions in PHP.
<?php
$givenString = "School";
$i=0;
while($givenString[$i]){
$i++;
if($givenString[$i] == o){
$givenString[$i] = 0;
}
}
echo $givenString;
?>
Result: Sch0ol
Required Result: Sch00l
2
Answers
Because your loop logic is out of order. Feed in the string
"ooooo"
and you’ll get"o0ooo"
out. It skips the first letter because the first thing you do is move the index ahead, and it stops after the first replacement because you’re testing the character that you just replaced, and"0"
type-juggles to boolean asfalse
.Move
$i++
to the end of the loop and you’ll get"00000"
, but alsoWarning: Uninitialized string offset 6
. This is because you’re relying on the error to break the loop. You need to bound the loop on thelength
of the string, not the content.So:
or we can condense that with
for
loop:For completeness, the un-quoted
o
in your post only works because pre-8.0 PHP assumed that unquoted constants were just "oopsies" meant to be strings and replaced them with their string equivalent, issuing a Notice likeNotice: Use of undefined constant o - assumed 'o'
, which can potentially have serious side-effects.This error also indicates that you’re using a version of PHP that is no longer supported, and you should ensure that you are writing code on a supported version.
In your current code, you are replacing all
o
to0
which is off-track with respect to replacingoo
to00
and also skipping the currento
at hand doesn’t make sense. Also, as already pointed out, matching a string with a string is better than comparing with justo
directly.You can instead match
o
witho
and check if string contained a previouso
or not. If it did, mark both previous and current location as0
, or else, leave it as is. Since you didn’t wish to use inbuilt functions, you can use null-coalescing operator(??) to check with the length of the string as well.Online Demo