phparraysarray-pusharray-key

Create PHP Array Dynamically


I want to create a PHP array with the following result. The array values will be passed dynamically.

array(
    __( 'Bedroom', "my-text-domain" ) => 'Bedroom', 
    __( 'Luxury', "my-text-domain" ) => 'Luxury', 
    __( 'Modern', "my-text-domain" ) => 'Modern', 
)

I tried both arraypush and key => value pair. But the expected output wasn't obtained.

array_push:

array_push($categories_dropdown, "__( '" . $cat_name . "',  'my-text-domain'  ) => '" . $cat_name . "'");

Array push results,

Array
(
    [0] => __( 'Uncategorized',  'my-text-domain'  ) => 'Uncategorized'
    [1] => __( 'Bedroom',  'my-text-domain'  ) => 'Bedroom'
    [2] => __( 'Luxury',  'my-text-domain'  ) => 'Luxury'
    [3] => __( 'Modern',  'my-text-domain'  ) => 'Modern'
    [4] => __( 'Office',  'my-text-domain'  ) => 'Office'
    [5] => __( 'Reception',  'my-text-domain'  ) => 'Reception'
    [6] => __( 'Vintage',  'my-text-domain'  ) => 'Vintage'
)

key => value pair :

$categories_dropdown["__( '".$cat_name."',  'my-text-domain'  )"] = $cat_name;

key => value pair results,

Array
(
    [__( 'Uncategorized',  'my-text-domain'  )] => Uncategorized
    [__( 'Bedroom',  'my-text-domain'  )] => Bedroom
    [__( 'Luxury',  'my-text-domain'  )] => Luxury
    [__( 'Modern',  'my-text-domain'  )] => Modern
    [__( 'Office',  'my-text-domain'  )] => Office
    [__( 'Reception',  'my-text-domain'  )] => Reception
    [__( 'Vintage',  'my-text-domain'  )] => Vintage
)

How can I result the above mentioned patterned array dynamically in PHP?


Solution

  • "__( '".$cat_name."', 'my-text-domain' )" is a string, and you need result of function execution, so remove quotes and call the __() function:

    $categories_dropdown[__($cat_name, 'my-text-domain')] = $cat_name;