Variables in php

PHP variables are used to store information.

PHP supports ten primitive types of variables:

To declare a php variable you must follow the rules below:

  • A variable must start with letter or underscore
  • variable name can not start with number or special characters
  • Variable name can only contain a-z, A-Z, 0-9 or _ characters
  • variable names are case sensitive

Booleans

A boolean expresses a truth value. It can be either TRUE or FALSE.

To declare a boolean you can use following code:

<?php

// declare a boolean
$isAdminUser = true;

// You can also cast other variables to boolean
// they will result as following
var_dump((bool) "");        // bool(false)
var_dump((bool) "0");       // bool(false)
var_dump((bool) 1);         // bool(true)
var_dump((bool) -2);        // bool(true)
var_dump((bool) "foo");     // bool(true)
var_dump((bool) 2.3e5);     // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array());   // bool(false)
var_dump((bool) "false");   // bool(true)
var_dump((bool) "0dssdf");  // bool(true)

Integers

An integer is a number of the set ℤ = {..., -2, -1, 0, 1, 2, ...}. Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation.

Followings are some of the examples of integers:

<?php

$a = 3434;        // decimal number
$a = -23;         // a negative number
$a = 0123;        // octal number (equivalent to 83 decimal)
$a = 0x1A;        // hexadecimal number (equivalent to 26 decimal)
$a = 0b11111111;  // binary number (equivalent to 255 decimal)

To find max and min of intergers you can use following constants:

  • PHP_INT_MAX
  • PHP_INT_MIN

Floats

Floating point numbers or floats or doubles or real numbers can be defined as below in php:

<?php

$a = 1.546; 
$b = 1.2e4; 
$c = 6E-10;

Floating point numbers have limited precision. Never trust floating number results to the last digit, and do not compare floating point numbers directly for equality.

Strings

A string in php is a series of bytes. A byte representing a single character. This means that php only supports 256 character set and therfore does not support unicode.

A string can be represented in different types as below:

Let's have a look at different types of strings with example:

<?php

# Example of single quoted string
echo 'This is an example of single quoted string' .PHP_EOL;

# Example of multiline
echo 'You can also have embedded newlines in 
        strings this way as it is
            okay to do' .PHP_EOL;

# Everything withing single quoted string is
# treated as literal string therefore in following
# example it wont create a new line
echo 'This will not expand: \n a newline' .PHP_EOL;

$twoApples = 2;

# Following example variable will
# not be escaped
echo 'Two apples: $twoApples' .PHP_EOL;


# Double quoted string can escape variables
echo "Two apples: $twoApples" .PHP_EOL;

# you can concat two strings
echo "string-1" . " string-2" .PHP_EOL;

# Heredoc string
echo <<<EOT
This is a first line
This is a second line
This is a third line
EOT;

# Nowdoc string
echo <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
Variable $twoApples wont be
escaped in nowdoc strings
EOD;

To specify a literal single quote, escape it with a backslash (\).

<?php

# escaping special character using single backslash
# when using single quoted strings
echo 'Arnold once said: "I\'ll be back"';

The most important feature of double-quoted strings is the fact that variable names will be expanded.

Heredoc text behaves just like a double-quoted string, without the double quotes.

To declare heredoc string you can use <<< operator followed by unique name in capital letter preffered and to end heredoc you must use the same unique name followed by colon.

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. Variables wont be escaped.

To declare nowdoc string you can use <<< operator followed by unique name in single quote in capital letter preffered and to end nowdoc you must use the same unique name followed by colon.

Arrays

Arrays in php are pair of keys and values. By default array uses numeric index in order starting with zero.

Thereare three types of arrays in php:

  • indexed arrays without keys
  • associative arrays with keys
  • multi-dimensional arrays

Example of indexed arrays without keys

<?php

# array of cars
$carsArray = ['mazda', 'toyota'];

# adding more values 
$carsArray[] = 'Jeep';

# to check the array values use
var_dump($carsArray);

# var_dump will print
# following result
array(3) {
  [0] =>
  string(5) "mazda"
  [1] =>
  string(6) "toyota"
  [2] =>
  string(4) "Jeep"
}

Example of associative array:

<?php

# declaring associative array with keys
$availableCars = [
    'mazda' => 3,
    'toyota' => 10
];

# adding more values
$availableCars['jeep'] = 20;

# check the values of array var_dump($availableCars); # result of var_dump will look like following array(3) { 'mazda' => int(3) 'toyota' => int(10) 'jeep' => int(20) }

Example of multi-dimensional array:

<?php

# declaring multi-dimensional array
$multiDimensionalArray = [
    "color" => "red",
    "cars"  => [
        "mazda" => [
            'gs sky' => 2,
            'gt sky' => 3
        ]
    ]
];

# print arrays in console or screen
print_r($multiDimensionalArray['cars']);

# result of print_r
Array
(
    [mazda] => Array
        (
            [gs sky] => 2
            [gt sky] => 3
        )

)

We will learn about more variables as we move on.

Interview Questions:

What is the output of following:

<?php

$a = '1';
$b = &$a;
$b = "2$b";

echo $a.", ".$b;

# answer
21, 21

# reason why value of $a is changed because $b is referencing $a 
# anytime change happens with $b will affect variable because of reference

What will be the output of the following PHP code?

<?php

$age = 10;
echo 'What is her age? \n She is $num years old';

Some other questions:

  • What are the different types of scalar types in php?
    • booleans
    • floats
    • integers
    • strings
  • What are the special types of variables in php?
    • resource
    • null
  • What is the difference between single and double quote strings?
    • single quote string does not parse variables it takes string as is and display
    • double quoted strings can escape variables and display their values
  • What is the difference between nowdoc and heredoc?
    • heredocs are double quoted strings
    • nowdocs are single quoted strings and does not escape variable