How to get all php array index from javascript? -


i have php file saved language string. content:

function lang($phrase) {     static $lang = array(         'step_one' => 'first step',         'step_two' => 'second step',          ... , on ...     );     return $lang[$phrase]; } 

essentially, when load javascript file want store array index in variable this:

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

this code line inserted in script, script available in php file. before of execute line have imported php file string translation available. i'm trying achieve, index of array, in variable lang. can load single string traduction php this:

lang('step_one'); 

but how can save array in javascript variable?

you can use array_keys retrieve array keys. need function return whole array on request. can leaving argument ($phrase) empty , if condition empty in lang function. need set default value $phrase in function not raise errors if don't pass argument function.

echo json_encode(array_keys(lang()); 

and function:

function lang($phrase = "") {     static $lang = array(         'step_one' => 'first step',         'step_two' => 'second step',          ... , on ...     );      if(empty($phrase)) {         return $lang;     } else {         if(isset($lang[$phrase])) { //isset make sure requested string exists in array, if doesn't - return empty string (you can return else if want             return $lang[$phrase];         } else {             return '';         }     } } 

i added isset make sure requested element exists in language array. prevent raising warnings.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -