I am having trouble returning a value from a multidimensional array using a key ONLY when I externalize to create a function.
To be specific, the following code will work when inline in a page:
<?php
foreach ($uiStringArray as $key) {
$keyVal = $key['uid'];
if($keyVal == 'global001') echo $key['uiString'];
}
?>
However, if I externalize the code as a function, like so:
function getUIString($myKey) {
// step through the string array and find the key that matches the uid,
// then return uiString
$myString = "-1";
foreach ($uiStringArray as $key) {
$keyVal = $key['uid'];
if($keyVal == 'global001') {
$myString = $key['uiString'];
}
}
return $myString;
}
And then call it like this:
<?php getUIString('global001'); ?>
It always returns -1, and will do so even if I use an explicit key in the function rather than a variable. I can't understand why this works inline, but fails as a function.
I'm a relative PHP noob, so please forgive me if this includes a glaring error on my part, but I've searched all over for discussion of this behavior and开发者_JS百科 found none.
All help appreciated.
i think you need to take a look at PHP's Variable Scope. To problem is that PHP isn't typical of other languages where a variable defined outside of a function is visible within. You need to use something like the $GLOBALS
variable or declare the variable global to access it.
To better illustrate, picture the following:
$foo = "bar";
function a(){
// $foo is not visible
echo $foo;
}
function b(){
global $foo; // make $foo visible
echo $foo;
}
function c(){
// acccess foo within the global space
echo $GLOBALS['foo'];
}
The same is basically holding true for your $uiStringArray
variable in this scenario.
This is a problem with variable scope, see Brad Christie's answer for more details on variable scope.
As for your example, you need to either pass the array to the function or create it inside the function. Try:
function getUIString($myKey, $uiStringArray = array()) {
// step through the string array and find the key that matches the uid,
// then return uiString
$myString = "-1";
foreach ($uiStringArray as $key) {
$keyVal = $key['uid'];
if($keyVal == 'global001') {
$myString = $key['uiString'];
break;
}
}
return $myString;
}
And call the function using
<?php getUIString('global001', $uiStringArray); ?>
You are having this problem because you are overriding you $mystring variable even if it matches. Send your array as your parameter. It is unknown to your function.You just use break if variable matches
function getUIString($myKey, $uiStringArray=array()) { // step through the string array and find the key that matches the uid, // then return uiString $myString = "-1"; foreach ($uiStringArray as $key) { $keyVal = $key['uid']; if($keyVal == 'global001') { $myString = $key['uiString']; break; } } return $myString; }
精彩评论