php – How to return a specific variable from inside a function?

Question:

In this code I gave a return $array and I'm using the data inside the foreach , so far so good.

I would also like to use the $url_controle variable there inside the file I called the function.

Question: How can I print this variable there in another file? I gave a return $url_controle but it didn't seem to work.

function list_all_pages() {

    $url_controle = $_SERVER['REQUEST_URI'];
    $url_controle = explode('/', $url_controle);
    $url_controle = $url_controle[2];

    global $pdo;

    $sql    = "SELECT * FROM tb_paginas WHERE tipo = '$url_controle' ORDER BY ID DESC";
    $exc    = $pdo->query($sql);
    $cnt    = $exc->rowCount();
    $array  = $exc->fetchAll(PDO::FETCH_ASSOC);

    return $array;

}

################
EM OUTRO ARQUIVO
################

$pages = list_all_pages();

foreach ($pages as $valores) {
    echo $valores['ID'];
    echo $valores['titulo'];
}

Answer:

You can create a return array with the desired information, then your code would look like this:

    function list_all_pages() {

        $url_controle = $_SERVER['REQUEST_URI'];
        $url_controle = explode('/', $url_controle);
        $url_controle = $url_controle[2];

        global $pdo;

        $sql    = "SELECT * FROM tb_paginas WHERE tipo = '$url_controle' ORDER BY ID DESC";
        $exc    = $pdo->query($sql);
        $cnt    = $exc->rowCount();
        $array  = $exc->fetchAll(PDO::FETCH_ASSOC);

        $retorno = array("url_controle" => $url_controle, "pages" => $array);
        return $retorno;

}

IN ANOTHER FILE

$pages = list_all_pages();
echo $pages['url_controle']; //valor que vc deseja obter

foreach ($pages['pages'] as $valores) {
    echo $valores['ID'];
    echo $valores['titulo'];
}
Scroll to Top