simply adding code to php function

758

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
211

Answer

Solution:

$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); 

People are also looking for solutions to the problem: php - Vue Resource Post Request Content-Type

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.