PHP Basic, Output & Types

Basic

Embed PHP code

<?php
...
?>

Note "?>" is not required if the file only contains PHP script (actually more desirable)

<?php
...

Add PHP Code inside HTML

<html>
<head>
  <title>Basic</title>
</head>
<body>
  <?php
      echo "Some PHP Code";
  ?>
</body>
</html>

Add text/HTML between PHP code

<?php
  $v1 = 4;
  $v2 = 5;
?>

<?php if ($v1 < $v2) { ?>
  <b>Embed text or HTML between PHP code</b>
<?php } ?>

Sample PHP code

<?php
  /*
    Multiple lines comment
  */
  # Single line comment
  // Another single line comment

  $start = TRUE;           # Variable always starts with a $ sign
  echo $start;             # Output the value of $start: 1

  $start = 1.2;            # Re-assign $start to a different type: PHP is loosely typed

  echo 'value= ', $start;  # Output multiple parameters
  var_dump($start);        # For debugging, dump the type & value of $start: double(1.2)

Output PHP Value

echo 'value= ', $a;        # Output one or more parameters
echo 'value with new line' . "\n";

print_r($a);               # Nicer format than echo
var_dump($a);              # For debugging, dump the type & value of $start: double(1.2)

Output a variable to a string

$s = print_r($a, 1);

Output to the PHP error log

error_log("my error");
  • The location of the error log is defined in "error_log" of the php.ini

Output a variable value to the PHP error log

error_log(print_r($a, 1));

PHP Assignment Statements

<?php
$v1 = $v2 = 10;
$v3 = $v1++;               # Increment $v1 after the assignment
$v4 = ++$v1;               # Increment $v1 before the assignment
$v4 += $v1;                # $v4 = $v4 + $v1

PHP Variable

  • Always start with $
  • Case sensitive ($Value & $value refer to 2 different variables)

Classes, functions and PHP reserved keywords are case insensitive. However, variable & constant are case sensitive

Note

For simplicity, we will omit

<?php
...

in our further code sample

Apache will display the PHP code as text if <?php is omitted in your code

PHP Types

PHP Integer

$i = 8;
$i = 0777;   # Octal
$i = 0xffff; # Hex

Pre-defined PHP Integer constant

PHP_INT_SIZE;  // Size of integer in byte
PHP_INT_MAX;   // Max integer

PHP Integer Math

$v = 3/2;           # double(1.5): Not 1
$v = (int) (8/3);   # int(2)
$v = round(8/3);    # double(3)

Integer division (unlike other programming language) returns a floating value in PHP

PHP boolean

$b = TRUE;
$b = FALSE;

All of the following evaluate to FALSE in a PHP conditional expression

$v = "";
if (!$v) {
    echo "empty string is evaluated to false";
}
  • 0, 0.0, "0"
  • "", NULL
  • Array with 0 element, NULL
  • SimpleXML with empty tags

Otherwise, the expression is evaluated to TRUE in a PHP conditional expression

$v = -1;
if ($v) {
    echo "-1 is evaluated to TRUE";
}

An un-assigned variable inside a conditional statement will generate a PHP notice in the error log

  • PHP Notice: Undefined variable
    if ($notAssignedYet) {
    ...
    }

    To verify whether it is defined first

    if (isset($a)) {
       ...
    }

PHP float

$d = 1.1;
$d = 1.1e3;

PHP NULL

$v = NULL;

Variables that have not been set or just unset() resume the value NULL

Default Value

Some functions (like echo) or operation expects a specific parameter type. If the parameter is un-initialized, it resumes the following default value

echo $not_initialized;   # Output ''
type Default
numeric type 0
boolean FALSE
String ''
Array array()

PHP Class (Object)

class Messenger
{
   var $v1 = 'test';

   function hello()
   {
      echo "hello";
   }
}

$p = new Messenger;
$p->hello();
var_dump($p->v1);                        # 'test'

Class comparison

if ($v instanceof Messenger)             # $v is class/sub-class/interface of Messenger
{
...
}

PHP Type Conversion & Casting

Numeric

$v = 1 + "3.5";                          # double(4.5)
$v = 2.3 + "some text";                  # double(2.3), String like "some text" is evaluated to 0
$v = 1 + "3 some text";                  # int(4)
$i = (int) 5/3;                          # $i = 1;

PHP Casting Function

Casting Functions Comment
(int), (integer)  
(bool), (boolean)  
(float), (double), (real)  
(binary) cast to binary string
(object) cast to object
(unset) cast to NULL

Float can be truncated to an integer using (int). If a function or operator is expecting an integer, the casting will be done automatically without (int).

Casting between PHP object and array

Convert a PHP Object to an array

class MyClass
{
    public $v1 = 'value';
}
$o = new MyClass;
$a = (array) $o;                      # Cast an object to an array
$a['v1'];                               # Access object instance variable $v1: 'value'

Convert an array to a PHP Object

$a = array('name' => 'value');
$o = (object) $a;                     # Cast an array to an ojbect
$o->name;                             # Access array element with key 'name': 'value'

PHP String Conversion

(string) converts other type to a string

$s = (string) FALSE;
$s = (string) "";

Conversion Rules

  • A TRUE value is converted to "1"
  • A FALSE value is converted to ""
  • Numeric value is converted to its corresponding number string
  • Array is convert to the string "Array"
  • Object is convert to the string "Object"

PHP Array Conversion

Cast to an array

$a = (array) "abc";
var_dump($a);          # array(1) { [0]=> string(3) "abc" }

Object

Convert to a PHP Object

$o = (object) 'hello';                   # Convert to object type

Convert from a PHP Object

echo $o->scalar;                         # 'hello'

PHP Type Checking

Verify if $val is an integer

if (is_int($val)) {
   ...
}
Type Checking Functions
is_array
is_binary
is_bool
is_buffer
is_callable
is_double
is_float
is_int
is_integer
is_long
is_null
is_numeric
is_object
is_real
is_resource
is_scalar
is_string
is_unicode

Return the variable type as a string

gettype($a);