简体   繁体   中英

Combine two variables into one

I try to merge or combine two variables into one new variable.

My Snippet looks like this:

<?php
  $text_headline = "dat headline";

  for ($i = 1; $i <= $text_text; $i++) {

    echo '$text_headline.$i';
  }
?>

But this didn't work, of course.

I also tried

$text_headline_combo = {$text_headline.$i};

But doesn't work as well. It sends me an error message.

Parse error: syntax error, unexpected '{' in /...

Does anybody have other solution for me? Much thanks in advance!

String interpolation is only recognized in double quotes.

Try

echo "$text_headline.$i";

If I understand your comments correctly, you have a series of headlines like

$text_headline1 = 'Some headline';
$text_headline2 = 'Another headline';

You want to output them in your loop. You can use a double $

<?php
  $text_headline1 = 'Some headline';
  $text_headline2 = 'Another headline';

  for ($i = 1; $i <= $text_text; $i++) {

    $headlineVar = 'text_headline' . $i;
    echo $$headlineVar;
  }
?>

This is called Variable variables .

Try this:

$text_headline .= $i;

The .= is called a concatenating assignment operator and it appends the argument on the right side to the argument on the left side.

Read more about it here and here .

I think that's what you need:

<?php
  $text_headline = "dat headline";

  for ($i = 1; $i <= $text_text; $i++) {
     $text_headline .= $i;
  }

?>

Replace the single quotes on your echo line with double quotes. Double quotes parse variables, single quotes do not.

As Austin mentioned, you need to use double quotes for string interpolation such as "$text_1.$text_2" . Personally I like to separate out my strings as such "string 1" . "string 2" "string 1" . "string 2" so that the code is easier to read.

It is also useful to use the .= operator. ex. $text_1 .= $text_to_add;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM