0

I am trying to create a new variable out of part of another variables value. I have gone through multiple other SO threads but I am trying to figure out how to make the new variable its own instance. Making a variable out of another variables' value in php (php basics)

I have this variable: $id = 0 ;

I want to create: $limit_$id (IE: $limit_0) that I can reference just as native variable. I believe I can do this: $${'limit_'.$id}, but is there any way to actually end up with $limit_0 so I don't have to reference it as $${'limit_'.$id) ???

2
  • 2
    This is a bit of a code smell. You're likely better off just using an array, like $limit[$id]. Commented Aug 23, 2023 at 22:47
  • 1
    @rolinger The request seems to make no sense: if you already know the final name of the variable, you don't need to compose it with other variables. Commented Aug 23, 2023 at 22:52

2 Answers 2

2

What do you mean by "reference it as $${'limit_'.$id)"?

You can do something like:

$id = 0;

${'limit_' . $id} = 'foo';

echo $limit_0; // foo

But, as someone already pointed out in a comment: if you already know the name of the final variable, you can just define it directly with that name.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the form ${"limit_$id"}, but it's a variation of what you already proposed:

<?php
$id = 1;
$limit_1 = 42;
echo ${"limit_$id"}, PHP_EOL;
${"limit_$id"} = 43;
echo ${"limit_$id"}, PHP_EOL;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.