0

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?

8
  • __() is a function, why do you enclose it in quotes? Commented Mar 5, 2020 at 9:20
  • The array is required to create a custom element in wpBakery plugin and, it's the array pattern that the parameter accepts sir. When hard coding the values it works fine, now I want the values dynamically assigned Commented Mar 5, 2020 at 9:23
  • 3
    So why not $categories_dropdown[__( $cat_name, 'my-text-domain' )] = $cat_name;? Commented Mar 5, 2020 at 9:24
  • 1
    Yes, the function __() is called. And what do you expect? Commented Mar 5, 2020 at 9:33
  • 1
    '__( 'Bedroom', "my-text-domain" )' is a string. Why do you need this string instead of result of caliing __()? Commented Mar 5, 2020 at 9:53

1 Answer 1

2

"__( '".$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;
Sign up to request clarification or add additional context in comments.

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.