2

A string like (for example):

$s = "allo";

i wanted to replace its first character with he to become hello using the indexes, so i used

$s = "allo";
$s[0] = "he";
echo $s; 

the result i expected was hello but got hllo

is there a kind of a limit on changing the letters by indexes in a string?

2 Answers 2

2

When using a string as an array, you are referencing individual characters, so $s[0] is the a, trying to fit two charachters into 1 isn't going to work. The easiest way to do it is to take the new string and append the old value from the second position (I've used substr($s,1))

$s = "alalo";
$res = "he".substr($s,1);
echo $res; 

gives...

helalo
Sign up to request clarification or add additional context in comments.

Comments

1

In PHP a string can be formed using index on the string itself without problem but You can't use $s[0] = "he"; because this way you are trying to assing to a single location two char .. so php assign just the first .. for change both the chars you must use the replace function.

You could try using replace

 $res = str_replace($s[0], "he" ,$s );

But ass suggested by Nigel Ren this work if there only an occurrence of the $s[0] in the $s string otherwise you use a string concat and substring instead of a replace

1 Comment

because You want assign on index element two values . .$s[0] in a char position (is the memory location for a char not for two).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.