I have the following code:
$target = "abcwa";
for($w = 0; $w <=strlen($target)-1; $w++)
{
$str = str_split($target[$w],1); //a
$str_ = $str[$w];
echo "w:";$w;
echo $str_;
}// end for w
It is printing:
w:a
Warning: Undefined array key 1 in /in/n705C on line 8
w:
Warning: Undefined array key 2 in /in/n705C on line 8
w:
Warning: Undefined array key 3 in /in/n705C on line 8
w:
Warning: Undefined array key 4 in /in/n705C on line 8
w:
Line 8 is $str_ = $str[$w];
.
However the goal is to print: w:aw:bw:cw:ww:a
What is wrong?
2
Answers
Your loop has:
This is more commonly done with:
But you don’t need any loops at all here. Start by splitting the string into an array of individual letters:
This gives you:
['a', 'b', 'c', 'w', 'a']
Then re-combine that array into a string, but with
"w:"
between each element:This gives you:
Then just tack on your leading
"w:"
:Which yields:
Alternatively, you could add a space to the start of your string, so that the split has one extra character at the start, for the implode to act on:
Which yields:
(Note there’s an extra space in the output in this case, if that matters.)
I would abandon your original code because it is verbose and has multiple failing components.
Instead, just use regex to insert your desired string before each character.
Codes: (Demo)
Or