sark9012
sark9012

Reputation: 5737

Name a variable on the fly

I am accepting a variable into a function.

For example, the variable is called $field and I then want to name a variable by what is inside the $field variable.

Say $field = 'randomName', I want my variable to be $randomName.

Is this possible?

Thanks.

Upvotes: 1

Views: 101

Answers (6)

Nir Alfasi
Nir Alfasi

Reputation: 53525

Yes it is possible:

$field = "randomName";
$$field = "test";
$$$field = "test 2";
echo $randomName . "\n"; //outputs: "test"
echo $test. "\n"; //outputs: "test 2"

Check this out

Upvotes: 1

Carsten
Carsten

Reputation: 18446

PHP has a language feature called variable variables. In your case:

$field = 'randomName';

$$field = "Hello world!";

echo $randomName; // prints out "Hello world!"

Upvotes: 1

user2258571
user2258571

Reputation: 11

It is possible (see "variable variables"), but this approach should be discouraged and it is often better to use a data structure (i.e. an array with keys) for this sort of dynamic operation.

Upvotes: 1

sybear
sybear

Reputation: 7784

$field = "randomName" ;
${$field} = "yeah" ;

${"randomName"} = "that works too" ;

Upvotes: 1

Kai Qing
Kai Qing

Reputation: 18833

You can assign variables as variable names.

$$field

This will do what it sounds like you're asking for.

Upvotes: 0

bwoebi
bwoebi

Reputation: 23777

You want variable variables?

See http://php.net/manual/en/language.variables.variable.php

Example

$varname = 'var';
$$varname = 'content';
print $var; // outputs 'content'

Upvotes: 0

Related Questions