logo

PHP - Documentation and Code Snippets

PHP is a scripting language for server-side development.

PHP Code Snippets

Hello world

<?php
function greetMe($name) {
  return "Hello, " . $name . "!";
}

$message = greetMe($name);
echo $message;
                

Objects

<?php

$fruitsArray = array(
  "apple" => 20,
  "banana" => 30
);
echo $fruitsArray['banana'];
                

Or cast as object

<?php

$fruitsObject = (object) $fruits;
echo $fruitsObject->banana;
                

Inspecting objects

<?php
var_dump($object)
                

Classes

class Person {
    public $name = '';
}

$person = new Person();
$person->name = 'bob';

echo $person->name;
                

Getters and setters

class Person 
{
    public $name = '';

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }
}

$person = new Person();
$person->setName('bob');

echo $person->getName();
                

isset vs empty

$options = [
  'key' => 'value',
  'blank' => '',
  'nothing' => null,
];

var_dump(isset($options['key']), empty($options['key'])); // true, false
var_dump(isset($options['blank']), empty($options['blank'])); // true, true
var_dump(isset($options['nothing']), empty($options['nothing'])); // false, true