Results: 133
PHP If statement CODE
If the current day is Friday the code will output "Have a nice weekend!" PHP datetime format: https://www.php.net/manual/en/datetime.format.php
$d = date("D");
if ($d == "Fri"){
    echo "Have a nice weekend!";
}
If the current hour is less than 20, the code will output "Have a good day!"
$t = date("H");
if ($t < "20") {
  echo "Have a good day!";
}
If
$age
is more than
18
, prints
Adult
$age = 20;
if ($age > 18) {
	echo 'Adult';	
}
Array types CODE
Indexed array
$colors = ["Red", "Green", "Blue"];
$colors[] = "Yellow";
Associative arrays
$student = [
	"name"=>"George", 
	"weight"=>77, 
	"height"=>1.8, 
	"male"=>true
];
$student["male"] = true;
echo 'George is ' . $student['weight'] . 'kg'."\n";
Multidimensional arrays
$students = [
	"George"=> [
		"name"=>"George", 
		"weight"=>77, 
		"height"=>1.8, 
		"male"=>true
	],
	"Alex"=> [
		"name"=>"Alex", 
		"weight"=>87, 
		"height"=>2.8, 
		"male"=>true,
		"parents"=> [
			"father"=>"David",
			"mother"=>"Marta",
		]
	],
	
];
echo 'Alex weighs ' . $students['Alex']['weight'] . 'kg'."\n";
echo "Alex's father is: " . $students['Alex']['parents']['father'];
Math functions CODE
Function
min()
finds the lowest value from its arguments
echo min(10, 15, 7, 9, 17)."\n"; // 7
Function
max()
finds the highest value from its arguments
echo max(10, 15, 7, 9, 17)."\n"; // 17
Function
count()
counts all elements in the array
echo count([10, 15, 7, 9, 17])."\n";
Function
round()
rounds a floating-point number to its nearest integer
echo(round(0.75))."\n";  // returns 1
echo(round(0.5))."\n";  // returns 1
echo(round(0.49))."\n";  // returns 0
Function
floor()
rounds the floating-point number down
echo floor(3.3)."\n";// 3  
echo floor(7.84)."\n";// 7 
echo floor(-4.8)."\n";// -5  
Function
ceil()
rounds the floating-point number up
echo ceil(3.3)."\n";// 4
echo ceil(7.84)."\n";// 8
echo ceil(-4.8)."\n";// -4
Function
rand()
generates a random number
echo rand()."\n";
// Generates a random number from the range
echo rand(10, 100)."\n";
Function
sqrt()
returns the square root of a number
echo sqrt(64)."\n";  // 8
Function
pow()
raises 2 to the power of 3
echo pow(2, 3)."\n";  // 8
Function
pi()
Returns PI value
echo pi()."\n";// 3.1415926535898
Function
abs()
returns the positive (absolute) value of a number
echo abs(-12)."\n";
Function
decbin()
converts decimal number into binary
echo decbin(2)."\n";// 10 
Differences between echo and print CODE
1.
echo
can take multiple parameters
echo 'one', 'two', 'three', "\n";
2.
print
statement returns 1
$print_returns = print('some text')."\n";
echo "print_returns Value: $print_returns" . "\n";
echo
prints 1 after
print
statement is executed
echo print "123", "\n";
3.
echo
is a little bit faster than
print
The function gets data table, passes to recursive function to get associative array back. Encodes the array to JSON and returns back to user:
public function getCategoryTreeJSON()
{
    $query = "  SELECT
                    c1.id,
                    c1.name,
                    c1.parent_id,
                    (
                        SELECT
                            COUNT(c2.id) 
                        FROM
                            categories AS c2 
                        WHERE
                            c2.parent_id = c1.id
                    )
                    AS children_count 
                FROM
                    categories AS c1";

    $categoryDetails = json_decode(json_encode(DB::select($query)), true);
    
    $array_tree = $this->getCategoryTreeArray($categoryDetails);

    return json_encode($array_tree);
}
Recursive function that returns multi level associative array. Base case: when
children_count
is equal to zero.
public function getCategoryTreeArray($items, $parent_id = 0)
{
    $branch = [];
    $array_JSON = [];  

    foreach ($items as $item) {
        if ($item['parent_id'] == $parent_id) {

            if ($item['children_count'] > 0) {
                
                $array_JSON[] = [
                    'id'=>$item['id'],
                    'title'=>$item['name'],
                    'subs'=>$this->getCategoryTreeArray($items, $item['id'])
                ];
                
            } else {
                
                $array_JSON[] = [
                    'id'=>$item['id'],
                    'title'=>$item['name']
                ];
            }
            
        }
    }
    return $array_JSON;
}
class Say {
    public function let() {
        echo 'Let' . " ";
        return $this;
    }
    public function me() {
        echo 'Me' . " ";
        return $this;
    }
    public function tell() {
        echo 'Tell' . " ";
        return $this;
    }
    public function you() {
        echo 'You' . " ";
        return $this;
    }
    public function something() {
        echo 'Something' . " ";
    }
}
$phrase = new Say;
$phrase->let()->me()->tell()->you()->something();
__get
and
__set
methods are called when there is an attempt either to use or to set a new value to any of the class property
class Person{
    public $firstName;
 
    public function __get($propertyName){
        echo "attempted to read property: $propertyName" . PHP_EOL;
    } 
    public function __set($propertyNane, $propertyValue){
        echo "attempted to set new value to property: $propertyNane" . PHP_EOL;
    } 
}
 
$p = new Person();
 
$p->firstName = 'Doe';
echo $p->firstName . PHP_EOL;
 
$p->lastName = 'John';
echo $p->lastName;
If the property is
public
, the methods are not going to be called (if the property does not exist, or exists but is not public, the methods will get called) If we make
$firstName
property
private
or
protected
, the methods will be called for the
$firstName
property
__get
,
__set
,
__call
and
__callStatic
are invoked when the method or property is inaccessible
we can not use $this (object properties) inside static methods
class Wheather {
    public $nonStatic = 0;
    public static $tempConditions = ['cold', 'mild', 'warm'];
    public static $someProperty = 5;

    static function celsiusToFarenheit($celsius) {
        return $celsius * 9 / 5 + 32 + $this->nonStatic;
    }
}

echo Wheather::celsiusToFarenheit(0);
echo "\n";
In this case we will get the error:
Fatal error:  Uncaught Error: Using $this when not in object context
PHP For loop CODE
if
has only one section:
Condition
if (Condition) {
    // Code to be executed
}
for
loop has three sections divided by
;
for (Initialization;   Condition;   Increment/Decrement) {
    // Code to be executed
}
The loop prints numbers from 0 to 10
for ($i = 0;  $i < 10;  $i ++) {
	echo $i . "\n";
}
User-defined functions CODE
Function that does something
function printGreeting() {
	print "Prints: Hello world!\n";
}
printGreeting();
Function that returns something
function returnGreeting() {
	return "Returns: Hello world!\n";
}
echo returnGreeting();
Parameterized function that doubles the number
function doubleMe($number) {
	$result = "$number times 2 is: " . $number * 2 . "\n";
	return $result;
}
echo doubleMe(4);
Function calculates the sum of two numbers
function add($num1, $num2) {
	$sum = $num1 + $num2;
	$result = "Sum of $num1 and $num2 is: $sum";
	return $result;
}
echo add(4, 5);
Results: 133