Matthias Stähle
Matthias Stähle

Reputation: 97

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!

Upvotes: 3

Views: 7400

Answers (6)

Robbert
Robbert

Reputation: 6582

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.

Upvotes: 2

Ethan
Ethan

Reputation: 2784

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" so that the code is easier to read.

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

Upvotes: 0

Pankaj Sharma
Pankaj Sharma

Reputation: 679

I think that's what you need:

<?php
  $text_headline = "dat headline";

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

?>

Upvotes: 1

simeg
simeg

Reputation: 1879

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.

Upvotes: 1

Nate
Nate

Reputation: 51

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

Upvotes: 0

Austin Brunkhorst
Austin Brunkhorst

Reputation: 21130

String interpolation is only recognized in double quotes.

Try

echo "$text_headline.$i";

Upvotes: 4

Related Questions