开发者

Print contents of an array and their key in PHP

so currently I have a PHP function that prints out the applications configuration:

function cconfig() {
global $config;
// If the user wants debug information shown:
if (SHOWDEBUG == true) {
    // If there is config information to show
    if (isset($config)) {
        cout("Variable $config is set.", "debug");
        foreach ($config as $current) {
         开发者_JAVA百科   echo $current."<br/>";
        }
    } else {
        cout("Variable &#36;config isn't set.", "debug");
    }
}

}

The output only shows the values of the array that it's at $current. For example:

Value1
Value2
Value3

How can I edit this function so instead of just showing the value at a given key, it also shows the key?

ConfigEntry1 = Value1
ConfigEntry2 = Value2
ConfigEntry3 = Value3


foreach ($config as $key => $current) {
    echo "$key = $current<br />";
}


Expose the key like so:

foreach ($config as $k => $v) {
    echo $k. ' ' . $v ."<br/>";
}

The two forms a foreach can take, from the manual:

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).

The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.


Change:

foreach ($config as $current) {
        echo $current."<br/>";
    }

to

foreach ($config as $key => $val) {
        echo $key." = " . $val . "<br/>";
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜