function addition( $x = 10 ){
echo $x + 10;
}
addition(40); // outputs : 50
addition(); // passing no value. outputs : 20
function addition( $x = 10, $y = 20 ){
echo $x + $y;
}
addition(5); // passing one argument. outputs : 25
addition(); // passing no value. outputs : 30
function print_arr(...$numbers) {
foreach ($numbers as $element) {
echo $element."\n";
}
}
echo print_arr(1, 2, 3, 4);
// outputs : 1 2 3 4
function display( $number ) {
if( $number <= 10 ){
echo "$number";
display ($number+1 );
}
}
display(0);
// outputs : 012345678910
$bool = TRUE;
if (is_null($bool))
{
echo 'Variable is NULL';
}
else
{
echo 'Variable is not NULL';
}
// outputs : Variable is not NULL
$x = 5;
$y = 10;
// Swapping Logic
$temp = $x;
$x = $y;
$y = $temp;
echo "After swapping: ";
echo "\n x = $x \n y = $y";
// outputs : x = 10 y = 5
• Swap two numbers without using a third variable
- Using arithmetic operation + and ?$x = 5;
$y = 10;
$x = $x + $y; // 15
$y = $x - $y; // 5
$x = $x - $y; // 10
echo "After swapping: ";
echo "\n x = $x \n y = $y";
// outputs : x = 10 y = 5
- Using arithmetic operation * and /
$x = 5;
$y = 10;
$x = $x*$y; // 50
$y = $x/$y; // 5
$x = $x/$y; // 10
echo "After swapping: ";
echo "\n x = $x \n y = $y";
// outputs : x = 10 y = 5
rand();
or rand(min,max);
For instance:
$x = rand(0,10);
echo $x;
// outputs : random integer between 0 and 10 (inclusive)
$num = 0;
$n1 = 0;
$n2 = 1;
echo "Fibonacci series for first 20 numbers: \n";
echo $n1.' '.$n2.' ';
while ( $num < 18 )
{
$n3 = $n2 + $n1;
echo $n3.' ';
$n1 = $n2;
$n2 = $n3;
$num = $num + 1;
}
// 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
range(low, high, step)
// third parameter is optional, Specifies the increment used in the range. Default is 1
For instance:// Return an array of elements from "0" to "20".increment by 5.
$number = range(0,20,5);
print_r ($number);
// outputs : 0 5 10 15 20
// Using letters - return an array of elements from "a" to "k"
$letter = range("a","k");
print_r ($letter);
// outputs : a b c d e f g h i j k
$alpha = range('A', 'Z');
for( $i = 0; $i < 10; $i++ ) {
for( $k = 10; $k > $i ; $k-- ){
echo $alpha[$i];
}
echo "\n";
}
Outputs : AAAAAAAAAA
BBBBBBBBB
CCCCCCCC
DDDDDDD
EEEEEE
FFFFF
GGGG
HHH
II
J
$int = 10;
echo "I. Value of \$int is: $int\n";
echo gettype("$int"); // outputs : string
• An integer is NOT converted to a string.
$int = 10;
echo "II. Value of \$int is: ".$int;