0

In the code below, is there a way to get the name of the array from within that same array so it doesn't have to be typed multiple times?

$awesome_array = array(
    'fruit'=>'apple',
    'name'=>'awesome_array', // Name of array here
    'you_are_an'=>'awesome_array' // Name goes here too
);

That is all.

3 Answers 3

3

Its not possible directly. But you can achieve this behavior by defining the name prior to defining the array.

Here is 3 ways to do it. There can be more. But I cant recall any other way right now.

Array name is in a string

$array_name = 'awesome_array';
$$array_name = array(
    'fruit'=>'apple',
    'name'=>$array_name, // Name of array here
    'you_are_an'=>$array_name // Name goes here too
);

Most common way

Pekka reminded me in the comments.

$awesome_array = array('fruit'=>'apple');
$awesome_array['name'] = 'awesome_array';
$awesome_array['you_are_an'] = 'awesome_array';

Dynamically collect the name

$awesome_array = array('fruit'=>'apple');
// dynamically extracting the name of last defined variable
list($name) = array_slice(array_keys(get_defined_vars()), -1 , 1);
$awesome_array['name'] = $name;
$awesome_array['you_are_an'] = $name;
Sign up to request clarification or add additional context in comments.

4 Comments

This is nice, but doing it on an entirely array basis instead of with variable variables would be nicer :)
Thats not possible as The variable is not yet defined.
I mean storing the array in an array itself $my_array_container[$array_name] = array(....)
@Pekka Yeah I agree. See my another new way. Pretty much dynamic.
0
$array_name = "awesome_array";
$$array_name = array(
    'fruit'=>'apple',
    'name'=> $array_name  // Name of array here
    'you_are_an'=>$array_name  // Name goes here too
}

Comments

0

Not sure I understood the question, but you can use variable variables:

$var = 'awesome_array';
$$var = array(
    'fruit'=>'apple',
    'name'=>$var, // Name of array here
    'you_are_an'=>$var // Name goes here too
);

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.