Gareth Gillman
Gareth Gillman

Reputation: 353

Creating unique variable names in PHP

I have a script which can be used multiple times per script, each instance of the script requires some php stuff to be done, I need to create a unique name for each instance variable e.g.

I need:

$typedbefore1 = get_post_meta( $text, '_cmb2_typed_text', true );
$typed1 = '"' . implode('","', $typedbefore1) . '"';

$typedbefore2 = get_post_meta( $text, '_cmb2_typed_text', true );
$typed2 = '"' . implode('","', $typedbefore2) . '"';

$typedbefore3 = get_post_meta( $text, '_cmb2_typed_text', true );
$typed3 = '"' . implode('","', $typedbefore3) . '"';

The variable $text is a number generated by the user so I can use that e.g.

$typedbefore.$text = get_post_meta( $text, '_cmb2_typed_text', true );
$typed.$text = '"' . implode('","', $typedbefore.$text) . '"';

That doesn't work (obviously), is there a way to do what I need?

Converted to arrays but my implode isn't working:

$typedbefore = array();
$typedbefore[$text] = get_post_meta( $text, '_cmb2_typed_text', true );
$typed = array();
$typed[$text] = '"' . implode('","', $typedbefore[$text]) . '"';

It's still storing the $typed as an array, how can I do the second part so it implodes the data from $typedbefore?

Upvotes: 0

Views: 745

Answers (2)

MarcoS
MarcoS

Reputation: 17711

You really should use arrays, as MightyPork suggested...:

$typedbefore = array();
$typedbefore[$text] = "value";

UPDATE: To answer OP last question: from here I see wordpress finction get_post_meta() returns array only if it's last parameter is false. But I see you use true, so it should return a single value. So you shouldn't use implode (which expects an array as 2nd parameter) with a single value. I don't really understand what's your definitive goal, so I can't give a more specific comment, sorry...

Upvotes: 2

vaso123
vaso123

Reputation: 12391

You can use variable variables like:

$varname = "typedbefore".$text;
echo $$varname;

This is the same, if you say:

echo $typedbefore1 //If $text == 1

See here.

But much more better, if your are collecting your data into an array, and use that.

Upvotes: 1

Related Questions