10

Possible Duplicate:
Can I use a generated variable name in PHP?

Am stuck here!

$part_one = "abc";
$v = "one";

echo $part_???; // should output "abc"

How do I modify ??? to reference $v?

Thanks!

Community
  • 1
  • 1
RC.
  • 155
  • 1
  • 3
  • 6

2 Answers2

18

You need variable variables:

echo ${'part_'.$v};
// or
$var = 'part_'.$v;
echo $$var;
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • Why would this ever be useful? Just curious... – Ed S. Nov 21 '09 at 09:13
  • 1
    Since variable can also be used to call functions (`${'part_'.$v}()` would call the `abc` function), you can use this to compact algorithms where only the name of the function may vary. Take the `imagecreatefrom…` functions for example: Just get the image type, append it to "imagecreatefrom" and call that function: `$func = "imagecreatefrom".$type; $func($filename);`. – Gumbo Nov 21 '09 at 10:03
  • Another example is: `$sides = array('front' => array(1,2), 'back' => array(2,3)); foreach ($sides as $side_name => $side_value) { ${'side_' . $side_name} = array_sum($side_value); };` At this point, you have `$side_front = 3` and `$side_back = 5`. Very useful to not repeat code that may work well in a foreach loop. – Charlie Schliesser Mar 14 '12 at 21:14
1

$_part$v;? maybe idk. I know you can do this:

$vname="variable";
$$vname="hello";
echo $variable;

//WOULD output "hello"

try this:

$name="_part";
$name=$name . $v;
$$name=$value;
Adam Fowler
  • 1,750
  • 1
  • 17
  • 18