Skip to content

Instantly share code, notes, and snippets.

@mmiliaus
Created August 23, 2012 16:15
Show Gist options
  • Save mmiliaus/3438171 to your computer and use it in GitHub Desktop.
Save mmiliaus/3438171 to your computer and use it in GitHub Desktop.

Basics

PHP code is surrounded by <?php ?> tags, like so:

<?php

// PHP code
echo "Hello World";

?>

Variables

Every variable starts with $ character, i.e.: $name, $products_count.

Functions

Code inside functions is sourrounded by { }. Functions can also have predefined arguments, i.e. $offset.

function get_products( $min_price, $offset = 0 ) {
  // getting products from DB
}
...

//both are legit calls
$products = get_products( 200 );
$products = get_products( 200, 10 );

Arrays and Hashes aka. Associative Arrays

Initialize

Array is initialized by invoking array(); function:

// empty array
$products = array();
// array with predefined elements
$products = array('Roadster', 'Model X');

Add element

$products[]= 'Model S';

Assign element to unique key

$products['electric cars'] = array('Roadster', 'Model X'); // [ 'electric cars'=> [ 'Roadster', 'Model X' ] ]

Accessing element

Let's print on the screen first element from $products array, sub-array which key is electric cars

echo $products['electric cars'][0];

Excepting Data From Outside

Data from web page to a PHP script can be passed throught GET or POST request. PHP script provides special superglobal variables. Two used most frequently are $_GET and $_POST, which are basically just associative-arrays (hashes).


// Reads 'name' parameter from URL that might look like this: http://localhost/index.php?name=John
echo $_GET['name'];

Small Greeter Application

Say we want to write a script that reads name parameter from the URL, and return a greeting for that person.

<?php

echo "Hello, ".$_GET['name']."!";

?>

Save code above to index.php. Open http://localhost/index.php?name=John. Vuolia, you should see

Hello, John!

As you might already guessed . is used to concatinate strings in PHP.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment