Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two variables into one

Tags:

variables

php

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!

like image 401
Matthias Stähle Avatar asked Apr 27 '26 16:04

Matthias Stähle


2 Answers

String interpolation is only recognized in double quotes.

Try

echo "$text_headline.$i";
like image 148
Austin Brunkhorst Avatar answered Apr 30 '26 06:04

Austin Brunkhorst


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.

like image 33
Robbert Avatar answered Apr 30 '26 05:04

Robbert