4

I'm trying to reference the key/value pair of an item in the same array:

$glossary_args = array(
    'name'          => 'Glossary Terms',
    'singular_name' => 'Glossary Term',
    'add_new'       => 'Add New Term',
    'edit_item'     => 'Edit Term',
    'search_items'  => 'Search'.$glossary_args["name"],
)

Is this even possible? If so, how?

2
  • 2
    Dupe of stackoverflow.com/questions/10358261/php-self-referencing-array Commented Aug 29, 2012 at 19:57
  • Perhaps, but I think that this is a little more specific. In addition to that, I would like to hear opinions on the best way to accomplish this if it is not possible. Commented Aug 29, 2012 at 20:03

2 Answers 2

18

You can use the fact that assignment is itself an expression in PHP:

$glossary_args = array(
    'name'          => ($name = 'Glossary Terms'),
    'singular_name' => 'Glossary Term',
    'add_new'       => 'Add New Term',
    'edit_item'     => 'Edit Term',
    'search_items'  => 'Search'.$name
)
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, I hoped I could do something like: functionName($arr = [ 'message' => 'hello', 'something_else' => $arr['message'] ]); or functionName([ 'message' => 'hello', 'something_else' => $self['message'] ]); but yours does work!
Your PHP kung fu is strong.
3

You can't do this when you're first defining the array - while you're inside array(), $glossary_args hasn't been created yet. Try this:

$glossary_args = array(
  'name' => 'Glossary Terms',
  'singular_name' => 'Glossary Term',
  'add_new' => 'Add New Term',
  'edit_item' => 'Edit Term'
);
// first we create the rest of $glossary_args, then we set search_items
$glossary_args['search_items'] = 'Search '.$glossary_args["name"];

3 Comments

Ok. I'm thinking that I will do the same thing that I did with search to add_new and edit_item. The idea is that I would only have to edit name and singular name and it would change the rest of the array. Would you recommend array_push at that point?
array_push can't set array keys, only values. You'd have to set add_new and edit_item the same way as search_items.
it'd be cleaner to use references . . . see my answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.