1

I need some help. in my project i have two variables,

  $name = 'john';
  $reg = 10;

and from this information i want create a array named $john10 dynamically. like

$john10 = new array();  

so please help me.

3
  • 3
    It's not a good idea. Explain the original task so that we could help you to solve the issue in a correct way, not just helping you writing crap. Commented Oct 28, 2013 at 6:33
  • there is one file that call each time in my magento module and i need dynamic array names for it as i mentioned information above. i know data should be organized like key ($abc[1] = ......) but here i can not use this type of logic Commented Oct 28, 2013 at 6:37
  • $john[10] = ... anything wrong with using real arrays? Commented Oct 28, 2013 at 6:38

3 Answers 3

2

Its not a good idea to do this what you want.

If you need something like that name may have different value against different reg, then you can use a 2D array as like:

store[name][reg] = new array();

Hope you analyses that and I redesign your code.

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

Comments

1

Although I would discourage doing anything like this in most circumstances, this is how you can do it:

<?php
$name = 'john';
$reg = 10;


${$name.$reg} = array();

11 Comments

"Although I would discourage doing anything like this in most circumstances" --- if you do, why not give a good advice?
Dear SO, I understand you all like reputation points, but STOP GIVING SILLY ADVICES. Thank you.
@zerkms To give proper advice on what to do instead of this construction, we'd have to know more about OP's situation. All we know is they want to concatenate 2 strings into a variable name.
OP asked, codefocus answered. OP did not ask if is this not a good idea, and has been offered warnings and alternatives... Can someone explain WHY this is not a good idea rather than ONLY giving advice other than what OP asked?
@codefocus: right. That's why you need to ask OP about the real issue, not start answering blindly.
|
1

Ok then you can use it though it is not best practice.

<?php
// The very top of your php script
$vars = get_defined_vars();

// Now do your stuff
$name = 'john';
$reg = 10;

// Get all the variables defined in current scope
$john10 = array_diff(get_defined_vars(),$vars);

print_r($john10);
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.