Reference key from same array

2019-04-09 17:19发布

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楼-- · 2019-04-09 17:37

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楼-- · 2019-04-09 17:38

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
)
查看更多
登录 后发表回答