PHP get variable in function from foreach loop

I am working on some plugin in wordpress and I have following array and foreach loop with function in it.

Problem is that somehow I always getting $locale_key variable same as $code when $locale_key variable is inside function.

Read More

Please help.

$languages = array(
    array('af', 'af', 'Afrikaans'),
    array('ar', 'ar', 'العربية', 'rtl'),
    array('az', 'az', 'Azərbaycan'),
    array('be', 'bel', 'Беларуская мова'),
    array('bg', 'bg_BG', 'български'),
    array('bs', 'bs_BA', 'Bosanski'),
    array('ca', 'ca', 'Català'),
    array('cs', 'cs_CZ', 'Čeština'));

$lang = $_SESSION['lang'];

foreach ($languages as $key => $value) {
    $locale_key = $languages[$key][1];
    $code = $languages[$key][0];
    echo $locale_key; // Here i get for example "bs_BA"
    add_shortcode( $code, function($atts, $content = null, $locale_key) {
        global $lang;
        echo $locale_key; // And then here i get "bs"
        if ($lang == $locale_key) {
            return $content;
        }
    }); 
}

Related posts

2 comments

  1. Try:

    $languages = array(
        array('af', 'af', 'Afrikaans'),
        array('ar', 'ar', 'العربية', 'rtl'),
        array('az', 'az', 'Azərbaycan'),
        array('be', 'bel', 'Беларуская мова'),
        array('bg', 'bg_BG', 'български'),
        array('bs', 'bs_BA', 'Bosanski'),
        array('ca', 'ca', 'Català'),
        array('cs', 'cs_CZ', 'Čeština'));
    
    $lang = $_SESSION['lang'];
    
    foreach ($languages as $key => $value) {
        $locale_key = $value[1];
        $code       = $value[0];
        add_shortcode( $code, function($atts, $content = null, $locale_key) {
            global $lang;
            if ($lang == $locale_key) {
                return $content;
            }
        }); 
    }
    

    When you use foreach($array as $key => $value) you can access the index via $key and the corresponding value via $value (even if that is an array too).

  2. <?php
    $array = [
        [1, 2, 3],
        [3, 4, 5],
    ];
    
    foreach ($array as list($a, $b, $c)) {
        // $a enthält das erste Element des verschachtelten Arrays
        // und $b enthält das zweite Element
        echo "A: $a; B: $b; C: $cn";
    }
    ?>
    

    Try something like above, im sure you will find the solution.

Comments are closed.