How do variables work in PHP? Print
Submit Cancel
Email this article

Close

You are here: Home > Website Support > PHP

Variables are assigned in a typical manner. Normal variables are preceded with a $ and assigned to with =. Any variable can be used in an array by including a key in square brackets after the variable.

For a regular array, a number is used as the key.
For an associative array, a quotes enclosed string (or another variable) is used.
The function ‘array’ can also be used to create arrays of either type.

The code below illustrates these features (lines beginning with “//” are comments):

// Normal variable assignment
    
$person "Bob";

    
// Assigning to a regular array
    
$fruit[0] "apple";
    
$fruit[1] "grape";
    
$fruit[2] "orange";

    
// Assigning to an associative array
    
$mother['kitten'"cat";
    
$mother['puppy'"dog";

    
// Using the array function for a regular array
    
$fruit = array('apple','grape','orange');

    
// Using the array function for an associative array
    
$mother = array('kitten' => 'cat''puppy' => 'dog');

    
// The following line prints "Bob's cat ate an orange."
    
echo "$person's $mother['kitten'] ate an $fruit[2].";
    
?> 

One of the most powerful features of PHP is its easy access to requested variables.  For instance, consider the following short form:

<form action="form_handler.php?posted=true" method="post">
<
input name="formvar">
<
input value="Submit Query" type="submit">
</
form

On submitting the form, the value of the variable “formvar” will be available to the form_handler.php script simply as

$_POST['formvar'

and the variable posted simply

$_GET['posted']

This is true for all POST and GET form calls.

Was this information helpful?

Yes No

Thank you for your feedback
We are delighted to find that our article resolved your query.

Thank you for your feedback
We will resolve your query as soon as possible.

Please take a few moments to comment on your unresolved query. Simply tell us what your problem is. We guarantee that we'll get back to you within two hours (during office hours) in response to your query.


  Partially resolved    Unresolved
Enter your query here:
Your name:
Your email address:
Contact number:
Customer number or domain name:
 
Preferred contact method: Email     Call me
Please enter the text in the picture below into the text box:
CAPTCHA Image:
ID Number:
 
  • Hosting for Beginners

    Step-by-step guide to hosting with Hetzner.

    VIEW NOW
  • Application Tutorials

    Use our installation guides to get up and running.

    VIEW NOW
  • Login Now

    Our award winning proprietary control panel empowers customers to manage their hosting environment.

    Take the Tour
  • Contact Us

    support@hetzner.co.za

    Phone: 0861-0861-08
    Fax: 0861 0861-09
    Contact Us