简体   繁体   中英

How to declare and use global variables

On this test page https://wintoweb.com/sandbox/question_2.php , the visitor can make searches in the DB and tick as many checkboxes as wished. When button [Accept...] is clicked, I want the result of all searches to be shown under 'Your selections so far'. Right now, only the last search is displayed. I tried using a global array to store the result of previous searches and increment it upon each new one. That's where I have a problem.

On top of file I have :

<?php
    global $all_authors;
    array ($all_authors, '');
?>

At bottom of file I have :

<?php
error_reporting(E_ALL);
ini_set('display_errors', true);

if(isset($_GET['search'])){
    //echo 'Search</br>';
} elseif(isset($_GET['display_this'])) {
    echo getNames();
}

function getNames() {
    $rets = '';
    if(isset($_GET['choices']) and !empty($_GET['choices'])){
      foreach($_GET['choices'] as $selected){
        $rets .= $selected.' -- ';
      }
//array_push($all_authors, $rets); // This is the problem
//print_r($allAuthors); // this too
echo '</br><b>Your selections so far :</b></br>';
    }
    return $rets;
}
?>

EXPECTED: Results of all previous searches to be listed ACTUAL: No go due to problem with array_push(). See function gatNames()

You should make the array global inside the function, so on top:

$all_authors = array();

In the bottom:

function getNames() {
    global $all_authors;

    // Do the rest of the stuff
}

You are returning $rets from your getNames function but not using it. You just need to use this variables $rets instead of Global Variable.


if(isset($_GET['search'])){
    //echo 'Search</br>';
} elseif(isset($_GET['display_this'])) {
    $rets = getNames(); //The $rets will hold the value returned by your function getName(). 
    if( !empty ( $rets ) ) {
       echo '</br><b>Your selections so far :</b></br>';
       echo $rets;
    }
}

You could remove the echo statement from inside your getNames Method.

function getNames() {
    $rets = '';
    if(isset($_GET['choices']) and !empty($_GET['choices'])){
      foreach($_GET['choices'] as $selected){
        $rets .= $selected.' -- ';
      }
    }
    return $rets;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM