1

I have a php file where I saved all language string. This is the content:

function lang($phrase)
{
    static $lang = array(
        'step_one' => 'First step',
        'step_two' => 'Second step',
         ... and so on ...
    );
    return $lang[$phrase];
}

Essentially, when I load a javascript file I want store all array index in a variable like this:

var Lang = <?php echo json_encode(lang()); ?>;

this code line is inserted in a script, this script is available in a php file. Now before of execute this line I have imported the php file where all string translation is available. What I'm trying to achieve, is get all index of this array, in the variable Lang. Actually I can load a single string traduction from php like this:

lang('step_one');

but how I can save this array in javascript variable?

3
  • You can use array_keys on the array if you just want all keys. php.net/array_keys Commented Jan 27, 2016 at 15:39
  • like <?php echo json_encode(lang(array_keys)); ?>; ? Commented Jan 27, 2016 at 15:40
  • 1
    Your function needs to return the whole array, then you can use array_keys. echo json_encode(array_keys(lang()); You can check if $phrase is empty in your function and if so return the whole array (you should check the variable anyway to not raise any warnings). Commented Jan 27, 2016 at 15:42

1 Answer 1

2

You can use array_keys to retrieve all array keys. To do that you need your function to return the whole array on request. You can do that with leaving the argument ($phrase) empty and do an if condition with empty in your lang function. You also need to set a default value for $phrase in your function to not raise any errors if you don't pass an argument to the function.

echo json_encode(array_keys(lang());

And the function:

function lang($phrase = "")
{
    static $lang = array(
        'step_one' => 'First step',
        'step_two' => 'Second step',
         ... and so on ...
    );

    if(empty($phrase)) {
        return $lang;
    } else {
        if(isset($lang[$phrase])) { //isset to make sure the requested string exists in the array, if it doesn't - return empty string (you can return anything else if you want
            return $lang[$phrase];
        } else {
            return '';
        }
    }
}

I also added isset to make sure the requested element exists in your language array. This will prevent raising warnings.

Sign up to request clarification or add additional context in comments.

2 Comments

@kingkero Oh, clickable links in code tags - nice to have - but nothing important.
@CharlotteDunois Yes, but still better (in my opinion) than an addendum of links

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.