Hezerac Hezerac - 2 months ago 8
PHP Question

simply adding code to php function

I want to create a php function with the following code but when I add this to a function it stops working:


Code works:

$arr = array(
"index.php" => $home,
"about.php" => $about,
"details.php" => $details
);
$url = basename($_SERVER['PHP_SELF']);

foreach($arr as $key => $value){

if($url == $key) {
echo $value;
}
}


Code Doesnt work:

function metaData() {
$arr = array(
"index.php" => $home,
"about.php" => $about,
"details.php" => $details
);
$url = basename($_SERVER['PHP_SELF']);

foreach($arr as $key => $value){

if($url == $key) {
echo $value;
}
}
}

metaData(); // NULL

Answer

$home, $about, and $details are all out of scope in your function. You need to pass them as parameters to that function for them to be available to the function itself.

function metaData($home, $about, $details) {
    $arr = array(
        "index.php" => $home, 
        "about.php" => $about, 
        "details.php" => $details
    );
    $url = basename($_SERVER['PHP_SELF']);

    foreach($arr as $key => $value){

        if($url == $key) {
            echo $value;
        }
    }
}

metaData($home, $about, $details); 
Comments