tags:

views:

42

answers:

6
+1  Q: 

Merge variables

We have $id and $title variables, which everytime change.

For each $id we should create a new variable $temp_title_%id%, and give to it $title's value.

Like:

$id = 10;
$title = 'Hello people!';
$temp_title_10 = 'Hello people!';

Tryed this (doesn't work):

$temp_title_ . $id = $title;

Thanks.

+1  A: 

I think it's a bad idea to do what you're trying to do, but here's how to do it anyways:

$GLOBALS["temp_title_".$id]=$title;

Alternatively, you could do this:

$varname="temp_title_".$id;
$$varname=$title;

The most correct way to do what I think you're trying to do would be to use an array:

// Somewhere in the PHP script:
$an_array=array();

// To assign:
$an_array[$id]=$title;

// To retrieve:
echo $an_array[$id];
icktoofay
The first approach is dangerous. It will not work inside a function and will mess with global variables.
Sebastián Grignoli
I agree... its a bad idea. I cant think of a use case where it would even make sense.
prodigitalson
@Sebastián: I know, and that's why I listed a second approach as well.
icktoofay
That's what I thought.
Sebastián Grignoli
+1  A: 

Use this:

$metavariable = "temp_title_".$id;
$$metavariable = $title;  // note the $$
Sebastián Grignoli
+2  A: 

If you're trying to persist your variables, it would probably be better to place them in an array if your $id variable will always be an integer.

$persistence_array = array();

while (some_requirement) {
    $id = ...;
    $title = ...;
    $persistence_array[$id] = $title;
}

If $id might also contain alpha-numeric data, then you could always use a hash / dictionary in the same way (with a small amount of additional logic you could even store multiple values for the same id).

DON'T DO THIS: If you absolutely must have variables then you can use variable variables But please, don't.

Sean Vieira
+6  A: 

How about using an array instead? An array is a much better way of storing multiple values. Much, much, much better.

$title_array = array();

$id = 10;
$title = 'Hello people!';
$title_array[$id] = $title;
John Kugelman
good way, thanks.
Happy
+1  A: 
${'temp_title_' . $id} = $title;
echo $temp_title_10;
zerkms
+1  A: 

Use variable variable of PHP http://php.net/manual/en/language.variables.variable.php

$variable = $title.'_'.$id
$$variable = 'hello, world!'
Hasan Khan