Reply to comment

Arrays, Passing Values, the $_GET[] Variable

In the previous chapter, we explored evaluation, evaluation order, variables, numbers and strings.

In this chapter, we explore how to send input to our short programs.

The most basic way to pass data from the web browser into our program is through the URL's query mechanism.

You've seen URLs that look like this:

http://foo.bar.com/index.php?id=100

The stuff to the right of "?" is called the query. The query is made up of pairs of names and values, separated by =; the pairs are separated by "&". Parameters are like variables, in that they assign values to named storage. In the above URL, the value of "id" is "100".

In PHP, these parameters are passed to a PHP script through the $_GET[] array variable.

Before discussing $_GET, let's quickly discuss arrays.

An array is an ordered list of values. You can assign an array to a variable, like this:

<?php
$a = array( "John", "Rose" );
?>

<?php
$a = array( "John", "Rose" );
echo $a[0];
?>

<?php
$a = array( "John", "Rose" );
echo $a[1];
?>

An associative array is a variation on the array, where, instead of referring to each element by number, you use a name.

<?php
$a = array( "host" => "John", "guest" => "Rose" );
echo $a["host"];
?>

<?php
$a = array( "host" => "John", "guest" => "Rose" );
echo $a["guest"];
?>

<?php
$a = array( "host" => "John", "guest" => "Rose" );
echo $a["Guest"];
?>

<?php
$a = array( "host" => "John", "guest" => "Rose" );
echo "<p>Host: $a[host]</p>";
echo "<p>Guest: $a[guest]</p>";
?>

Now, we can discuss the special variable $_GET[].

$_GET[] is an array that contains the parameters in the URL's query. Thus, if the URL is:

http://foo.com/test.php?id=100&filter=91770

Then the value of $_GET[] are:

$_GET["id"] = 100;
$_GET["filter"] = 91770;

Here's a script that will add two numbers:

<?php
$a = $_GET["a"];
$b = $_GET["b"];
echo $a + $b;
?>

<?php
$a = $_GET["a"];
$b = $_GET["b"];
echo "$a + $b";
?>

<?php
$a = $_GET["a"];
$b = $_GET["b"];
echo "$a + $b = " . ( $a + $b );
?>

Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <b> <dd> <dl> <dt> <i> <li> <ol> <u> <ul> <p> <br> <div> <pre> <code> <img><h1><h2><h3><h4> <blockquote>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options

.