Reputation: 351
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
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
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
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
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
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