Albi Hoti
Albi Hoti

Reputation: 351

PHP title depends from a variable

Im trying to display a title that depends from a variable, below is my code:

<?php 
$id = $_GET["id"];
$title1 = 'Title 1';
$title2 = 'Title 2';
$title3 = 'Title 3';
?>

Now how to print title2 if id='2', something like echo $title($id)

Upvotes: 2

Views: 145

Answers (6)

vusan
vusan

Reputation: 5331

Using $$ may be smart idea like:

<?php 
$id=1;
$id = "title".$id;
$title1 = 'Title 1';
$title2 = 'Title 2';
$title3 = 'Title 3';
echo $$id;
?>

Upvotes: 1

scottlimmer
scottlimmer

Reputation: 2268

You want to use something like echo ${"title{$id}"};

Upvotes: 2

MidnightLightning
MidnightLightning

Reputation: 6928

<?php 
$id = $_GET["id"];
$title_var = 'title'.$id; // Save the whole name of the variable as a string

$title1 = 'Title 1';
$title2 = 'Title 2';
$title3 = 'Title 3';

echo $$title_var; // Note the double dollar sign for a variable-variable
?>

Upvotes: 2

Fluffeh
Fluffeh

Reputation: 33512

The following should do the trick for you:

<?php 
    $id = $_GET["id"];
    switch($id)
    {
        case 1:
            $title = 'Title 1';
            break;
        case 2:
            $title = 'Title 2';
            break;
        case 3:
            $title = 'Title 3';
            break;
        default:
            $title = 'Something else';
            break;
    }

    echo $title;
?>

Upvotes: 5

Thibault Henry
Thibault Henry

Reputation: 841

You can user an Array :

$title = array(
     1 => 'Title 1',
     2 => 'Title 2',
     3 => 'Title 3'
);

And for have your title with your get :

$title[$_GET['title']];

Upvotes: 4

hsz
hsz

Reputation: 152216

Isn't it better to put your titles into an array ?

$id = (int) $_GET["id"];
$title = array(
  1 => 'Title 1',
  2 => 'Title 2',
  3 => 'Title 3'
);

echo $title[$id];

Upvotes: 7

Related Questions