Welcome to WebmasterWorld Guest from 54.145.173.147

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Appending multiple strings with same text

   
2:46 am on Mar 7, 2014 (gmt 0)



This should be a day 1 question, and I'm almost embarrassed to ask! LOL

Let's say I have:

$a = "apple";
$b = "banana";

Now, I want to say:

$a .= " is a fruit"; // apple is a fruit
$b .= " is a fruit"; // banana is a fruit

Is there a way to combine this in to one statement, so that I don't have to put " is a fruit" twice? Without creating a third variable, I mean.

I know that this doesn't work, but to give you an idea of what I mean, something like:

$a .= $b .= " is a fruit";

(Note for other readers, this doesn't work because it appends $b to $a first, making $a = "applebanana is a fruit")
8:27 am on Mar 7, 2014 (gmt 0)

10+ Year Member



Would it really make much of a difference to add a 3rd variable?

If so, why not just put all your 'fruits' into an array, and loop through them appending the extra text?
9:02 am on Mar 7, 2014 (gmt 0)



It wouldn't make much of a difference at all to add a 3rd variable, really. In fact, that's what I usually do. This is just something I find myself doing on occasion, though, and I thought that there might be a "cleaner" way of doing it that I didn't know.

So I guess it's just for my own education, really.
1:22 pm on Mar 7, 2014 (gmt 0)

10+ Year Member



I think a solution will normally be dictated by the context in which you are coding. If you had hundreds of fruits, for example, you would really be better off with a loop!
8:42 pm on Mar 8, 2014 (gmt 0)

10+ Year Member



If you had hundreds of fruits, for example, you would really be better off with a loop!


Precisely what I was thinking