Categories
Beginner

Basic PHP Tutorial (Part 01)

Variables in PHP

No Typing

  • You can assign anything to a PHP variable (as opposed to java, for example)
  • Notice the dollar sign, each variable in PHP starts with a $ sign.
// variable with number
$var = 1; // ‘var’ can be anything
$var = 1.1;
// string
$var = "Hello world!";
// boolean
$var = false;
$var = true;

Strings

Strings are surrounded by quotes:

$var = "Hello"; // double quotes
echo $var; // Prints Hello

$var = 'Hello'; // single quote - the same
echo $var; // Prints Hello

$var = "Hello and 'Hello'"; // quotes in quotes
echo $var; // Prints Hello and 'Hello'

You can get the length of the string. Use strlen:

$var = "Hello";
echo strlen($var); // prints 5

$var = " Hello "; // spaces are characters too!
echo strlen($var); // prints 7

You can concatenate strings. Use the.operator:

$var = "Hello";
echo $var; // Prints Hello

$var = $var . " world!"; // concatenates the strings, notice the .
echo $var; // prints Hello world!

Boolean Operators

  • >,>=,<,<=,==,!=
// what will be printed?
$var1 = 2;
$var2 = 3;
if($var1 > $var2){
    echo "True!";
}else{
    echo "False!";
}
  • && – and
// what will be printed?
$var1 = "Hello";
$var2 = "world";
if(strlen($var1) == strlen($var2) && $var1!=$var2){
    echo "True!";
}else{
    echo "False!";
}
  • || – or
// what will be printed?
$var1 = "Hello";
$var2 = "world";
if(strlen($var1) < strlen($var2) || $var1==$var2){
    echo "True!";
}else{
    echo "False!";
}
  • ! – not
// what will be printed?
$var = "Hello";
if(!$var){
    echo "True!";
}else{
    echo "False!";
}

Leave a Reply

Your email address will not be published. Required fields are marked *