tentang perintah __DIR__ mundur 1 folder
======www.w3schools.com====== lanjut: PHP Loops
----batas---- PHP match Expression
$result = match($expression) {
condition1 => returnvalue1,
condition2 => returnvalue2,
condition3, condition4 => returnvalue3,
default => defaultvalue,
}
$favcolor = "red";
$text = match($favcolor) {
"red" => "Your favorite color is red!",
"blue" => "Your favorite color is blue!",
"green" => "Your favorite color is green!",
default => "Your favorite color is neither red, blue, nor green!",
};
echo $text;
Match Multiple Values
$d = 3;
$text = match($d) {
1, 2, 3, 4, 5 => "The week feels so long!",
6, 0 => "Weekends are best!",
default => "Invalid day",
};
echo $text;
The default Keyword
$favcolor = "pink"; // no conditions will match this
try {
$text = match($favcolor) {
"red" => "Your favorite color is red!",
"blue" => "Your favorite color is blue!",
"green" => "Your favorite color is green!",
};
} catch (\UnhandledMatchError $e) {
var_dump($e);
}
echo $text;
PHP switch Statement The PHP switch Statement
switch (expression) {
case label1:
//code block
break;
case label2:
//code block;
break;
case label3:
//code block
break;
default:
//code block
}
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
The PHP break Keyword
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
case "blue":
"Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
The PHP default Keyword
$d = 4;
switch ($d) {
case 6:
echo "Today is Saturday";
break;
case 0:
echo "Today is Sunday";
break;
default:
echo "Looking forward to the Weekend";
}
Combining Cases
$d = 3;
switch ($d) {
case 1:
case 2:
case 3:
case 4:
case 5:
echo "The week feels so long!";
break;
case 6:
case 0:
echo "Weekends are best!";
break;
default:
echo "Something went wrong";
}
PHP Operators
Operator Name Example Result Try it
+ Addition $x + $y Sum of $x and $y
- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y
% Modulus $x % $y Remainder of $x divided by $y
** Exponentiation $x ** $y Result of raising $x to the $y'th power
PHP Assignment Operators
Assignment Same as... Description Try it
$x = $y $x = $y Assign (the left operand is set to the value of the expression on the right)
$x += $y $x = $x + $y Add and assign
$x -= $y $x = $x - $y Subtract and assign
$x *= $y $x = $x * $y Multiply and assign
$x /= $y $x = $x / $y Divide and assign
$x %= $y $x = $x % $y Modulus and assign
PHP Comparison Operators
Operator Name Example Result Try it
== Equal $x == $y Returns true if $x is equal to $y
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same type
!= Not equal $x != $y Returns true if $x is not equal to $y
<> Not equal $x <> $y Returns true if $x is not equal to $y
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type
> Greater than $x > $y Returns true if $x is greater than $y
< Less than $x < $y Returns true if $x is less than $y
>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
<=> Spaceship $x <=> $y Returns an integer less than, equal to, or greater than zero, depending on if $x is less than, equal to, or greater than $y. Introduced in PHP 7.
PHP Increment / Decrement Operators
Operator Same as... Description Try it
++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
Operator Name Example Result Try it
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true
PHP String Operators
Operator Name Example Result Try it
. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2
.= Concatenation assignment $txt1 .= $txt2 Appends $txt2 to $txt1
PHP Array Operators
Operator Name Example Result Try it
+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have the same key/value pairs
=== Identity $x === $y Returns true if $x and $y have the same key/value pairs in the same order and of the same types
!= Inequality $x != $y Returns true if $x is not equal to $y
<> Inequality $x <> $y Returns true if $x is not equal to $y
!== Non-identity $x !== $y Returns true if $x is not identical to $y
PHP Conditional Operators
Operator Name Example Result Try it
?: Ternary $x = expr1 ? expr2 : expr3 Returns the value of $x.
The value of $x is expr2 if expr1 = TRUE.
The value of $x is expr3 if expr1 = FALSE
?? Null coalescing $x = expr1 ?? expr2 Returns the value of $x.
The value of $x is expr1 if expr1 exists, and is not NULL.
If expr1 does not exist, or is NULL, the value of $x is expr2.
Introduced in PHP 7
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
$y = 6;
echo $x + $y;
?>
</body>
</html>
16
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
$y = 6;
echo $x - $y;
?>
</body>
</html>
4
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
$y = 6;
echo $x * $y;
?>
</body>
</html>
60
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
$y = 6;
echo $x / $y;
?>
</body>
</html>
1.6666666666667
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
$y = 6;
echo $x % $y;
?>
</body>
</html>
4
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
$y = 3;
echo $x ** $y;
?>
</body>
</html>
1000
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
echo $x;
?>
</body>
</html>
10
<!DOCTYPE html>
<html>
<body>
<?php
$x = 20;
$x += 100;
echo $x;
?>
</body>
</html>
120
<!DOCTYPE html>
<html>
<body>
<?php
$x = 50;
$x -= 30;
echo $x;
?>
</body>
</html>
20
<!DOCTYPE html>
<html>
<body>
<?php
$x = 20;
$x += 100;
echo $x;
?>
</body>
</html>
120
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$x *= 6;
echo $x;
?>
</body>
</html>
30
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
$x /= 5;
echo $x;
?>
</body>
</html>
2
<!DOCTYPE html>
<html>
<body>
<?php
$x = 15;
$x %= 4;
echo $x;
?>
</body>
</html>
3
<!DOCTYPE html>
<html>
<body>
<?php
$x = 100;
$y = "100";
var_dump($x == $y); // returns true because values are equal
?>
</body>
bool(true)
<!DOCTYPE html>
<html>
<body>
<?php
$x = 100;
$y = "100";
var_dump($x === $y); // returns false because types are not equal
?>
</body>
</html>
<?php
$x = 100;
$y = "100";
var_dump($x != $y); // returns false because values are equal
?>
bool(false)
<!DOCTYPE html>
<html>
<body>
<?php
$x = 100;
$y = "100";
var_dump($x <> $y); // returns false because values are equal
?>
</body>
</html>
bool(false)
<!DOCTYPE html>
<html>
<body>
<?php
$x = 100;
$y = "100";
var_dump($x !== $y); // returns true because types are not equal
?>
</body>
</html>
bool(true)
<!DOCTYPE html>
<html>
<body>
<?php
$x = 100;
$y = 50;
var_dump($x > $y); // returns true because $x is greater than $y
?>
</body>
</html>
bool(true)
<!DOCTYPE html>
<html>
<body>
<?php
$x = 50;
$y = 50;
var_dump($x <= $y); // returns true because $x is less than or equal to $y
?>
</body>
</html>
bool(true)
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$y = 10;
echo ($x <=> $y); // returns -1 because $x is less than $y
echo "<br>";
$x = 10;
$y = 10;
echo ($x <=> $y); // returns 0 because values are equal
echo "<br>";
$x = 15;
$y = 10;
echo ($x <=> $y); // returns +1 because $x is greater than $y
?>
</body>
</html>
-1
0
1
PHP if Statements PHP Conditional Statements PHP - The if Statement
if (condition) {
// code to be executed if condition is true;
}
if (5 > 3) {
echo "Have a good day!";
}
$t = 14;
if ($t < 20) {
echo "Have a good day!";
}
PHP if Operators
$t = 14;
if ($t == 14) {
echo "Have a good day!";
}
Operator Name Result Try it
== Equal Returns true if the values are equal
=== Identical Returns true if the values and data types are identical
!= Not equal Returns true if the values are not equal
<> Not equal Returns true if the values are not equal
!== Not identical Returns true if the values or data types are not identical
> Greater than Returns true if the first value is greater than the second value
< Less than Returns true if the first value is less than the second value
>= Greater than or equal to Returns true if the first value is greater than, or equal to, the second value
<= Less than or equal to Returns true if the first value is less than, or equal to, the second value
PHP Logical Operators
$a = 200;
$b = 33;
$c = 500;
if ($a > $b && $a < $c ) {
echo "Both conditions are true";
}
Operator Name Description Try it
and And True if both conditions are true
&& And True if both conditions are true
or Or True if either condition is true
|| Or True if either condition is true
xor Xor True if either condition is true, but not both
! Not True if condition is not true
$a = 5;
if ($a == 2 || $a == 3 || $a == 4 || $a == 5 || $a == 6 || $a == 7) {
echo "$a is a number between 2 and 7";
}
PHP if...else Statements PHP - The if...else Statement
if (condition) {
// code to be executed if condition is true;
} else {
// code to be executed if condition is false;
}
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
PHP - The if...elseif...else Statement
if (condition) {
// code to be executed if this condition is true;
} elseif (condition) {
// code to be executed if first condition is false and this condition is true;
} else {
// code to be executed if all conditions are false;
}
$t = date("H");
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
PHP Shorthand if Statements Short Hand If
$a = 5;
if ($a < 10) $b = "Hello";
echo $b
Short Hand If...Else
$a = 13;
$b = $a < 10 ? "Hello" : "Good Bye";
echo $b;
PHP Nested if Statements Nested If
$a = 13;
if ($a > 10) {
echo "Above 10";
if ($a > 20) {
echo " and also above 20";
} else {
echo " but not above 20";
}
}
<!DOCTYPE html>
<html>
<body>
<?php
$x = 100;
$y = "100";
var_dump($x === $y); // returns false because types are not equal
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<?php
$x = 100;
$y = "100";
var_dump($x === $y); // returns false because types are not equal
?>
</body>
</html>
bool(false)
PHP Magic Constants
Constant Description
__CLASS__ If used inside a class, the class name is returned.
__DIR__ The directory of the file.
__FILE__ The file name including the full path.
__FUNCTION__ If inside a function, the function name is returned.
__LINE__ The current line number of the file.
__METHOD__ If used inside a function that belongs to a class, both class and function name is returned.
__NAMESPACE__ If used inside a namespace, the name of the namespace is returned.
__TRAIT__ If used inside a trait, the trait name is returned.
ClassName::class Returns the name of the specified class and the name of the namespace, if any.
<!DOCTYPE html>
<html>
<body>
<h2>The __CLASS__ Constant</h2>
<p>This constant returns the class name:</p>
<?php
class Fruits {
public function myValue(){
return __CLASS__;
}
}
$kiwi = new Fruits();
echo $kiwi->myValue();
?>
</body>
</html>
The __CLASS__ Constant
This constant returns the class name:
Fruits
<!DOCTYPE html>
<html>
<body>
<h2>The __DIR__ Constant</h2>
<p>This constant returns the directory name of the file:</p>
<?php
echo __DIR__;
?>
</body>
</html>
The __DIR__ Constant
This constant returns the directory name of the file:
C:\awesomesites\w3schools\php
<!DOCTYPE html>
<html>
<body>
<h2>The __FILE__ Constant</h2>
<p>This constant returns the full path and the name of the file:</p>
<?php
echo __FILE__;
?>
</body>
</html>
The __FILE__ Constant
This constant returns the full path and the name of the file:
C:\awesomesites\w3schools\php\magic_const_file.php
<!DOCTYPE html>
<html>
<body>
<h2>The __FILE__ Constant</h2>
<p>This constant returns the full path and the name of the file:</p>
<?php
echo __FILE__;
?>
</body>
</html>
The __FILE__ Constant
This constant returns the full path and the name of the file:
C:\awesomesites\w3schools\php\magic_const_file.php
<!DOCTYPE html>
<html>
<body>
<h2>The __FUNCTION__ Constant</h2>
<p>This constant returns the function name:</p>
<?php
function myMessage(){
return __FUNCTION__;
}
echo myMessage();
?>
</body>
</html>
The __FUNCTION__ Constant
This constant returns the function name:
myMessage
<!DOCTYPE html>
<html>
<body>
<h2>The __LINE__ Constant</h2>
<p>This constant returns the current line number:</p>
<?php
echo __LINE__;
?>
</body>
</html>
The __LINE__ Constant
This constant returns the current line number:
9
<!DOCTYPE html>
<html>
<body>
<h2>The __METHOD__ Constant</h2>
<p>This constant returns both class and function name:</p>
<?php
class Fruits {
public function myValue(){
return __METHOD__;
}
}
$kiwi = new Fruits();
echo $kiwi->myValue();
?>
</body>
</html>
The __METHOD__ Constant
This constant returns both class and function name:
Fruits::myValue
<?php
namespace myArea;
function myValue(){
return __NAMESPACE__;
}
?>
<!DOCTYPE html>
<html>
<body>
<h2>The __NAMESPACE__ Constant</h2>
<p>This constant returns the name of the namespace:</p>
<?php
echo myValue();
?>
</body>
</html>
<?php
namespace myArea;
function myValue(){
return __NAMESPACE__;
}
?>
<!DOCTYPE html>
<html>
<body>
<h2>The __NAMESPACE__ Constant</h2>
<p>This constant returns the name of the namespace:</p>
<?php
echo myValue();
?>
</body>
</html>
<?php
namespace myArea;
function myValue(){
return __NAMESPACE__;
}
?>
<!DOCTYPE html>
<html>
<body>
<h2>The __NAMESPACE__ Constant</h2>
<p>This constant returns the name of the namespace:</p>
<?php
echo myValue();
?>
</body>
</html>
The __NAMESPACE__ Constant
This constant returns the name of the namespace:
myArea
<!DOCTYPE html>
<html>
<body>
<h2>The __TRAIT__ Constant</h2>
<p>This constant returns the trait name:</p>
<?php
trait message1 {
public function msg1() {
echo __TRAIT__;
}
}
class Welcome {
use message1;
}
$obj = new Welcome();
$obj->msg1();
?>
</body>
</html>
The __TRAIT__ Constant
This constant returns the trait name:
message1
<?php
namespace myArea;
class Fruits {
public function myValue(){
return Fruits::class;
}
}
?>
<!DOCTYPE html>
<html>
<body>
<h2>The ClassName::class Constant</h2>
<p>This constant returns the class name and name of the namespace (if any):</p>
<?php
$kiwi = new Fruits();
echo $kiwi->myValue();
?>
</body>
</html>
The ClassName::class Constant
This constant returns the class name and name of the namespace (if any):
myArea\Fruits
PHP Constants PHP define() Function
define(CONSTANT_NAME, value);
define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;
function myTest() {
define("GREETING", "Welcome to W3Schools.com!");
}
myTest();
echo GREETING;
PHP const Keyword
const CONSTANT_NAME = value;
const GREETING = "Welcome to W3Schools.com!";
echo GREETING;
PHP Array Constants
// Using define()
define("CARS", array("Volvo", "BMW", "Toyota"));
echo CARS[0];
// Using const
const ANIMALS = array("Cat", "Dog", "Horse");
echo ANIMALS[1];
PHP Math Functions PHP pi() Function
echo(pi());
PHP min() and max() Functions
echo(min(0, 150, -8, -200));
echo(max(0, 150, -8, -200));
PHP abs() Function
echo(abs(-6.7));
PHP sqrt() Function
echo(sqrt(64));
PHP round() Function
echo(round(3.60));
echo(round(0.49));
Random Numbers
echo(rand());
echo(rand(10, 100));
PHP Type Casting
$a = 5; // Integer
$b = 5.34; // Float
$c = "hello"; // String
$d = true; // Boolean
$e = NULL; // NULL
$a = (string) $a;
$b = (string) $b;
$c = (string) $c;
$d = (string) $d;
$e = (string) $e;
// Use var_dump() to verify the data type
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
var_dump($e);
Cast to Integer
$a = 5; // Integer
$b = 5.34; // Float
$c = "25 km"; // String
$d = "km 25"; // String
$e = "hello"; // String
$f = true; // Boolean
$g = NULL; // NULL
$a = (int) $a;
$b = (int) $b;
$c = (int) $c;
$d = (int) $d;
$e = (int) $e;
$f = (int) $f;
$g = (int) $g;
Cast to Float
$a = 5; // Integer
$b = 5.34; // Float
$c = "25 km"; // String
$d = "km 25"; // String
$e = "hello"; // String
$f = true; // Boolean
$g = NULL; // NULL
$a = (float) $a;
$b = (float) $b;
$c = (float) $c;
$d = (float) $d;
$e = (float) $e;
$f = (float) $f;
$g = (float) $g;
Cast to Boolean
$a = 5; // Integer
$b = 5.34; // Float
$c = 0; // Integer
$d = -1; // Integer
$e = 0.1; // Float
$f = "hello"; // String
$g = ""; // String
$h = true; // Boolean
$i = NULL; // NULL
$a = (bool) $a;
$b = (bool) $b;
$c = (bool) $c;
$d = (bool) $d;
$e = (bool) $e;
$f = (bool) $f;
$g = (bool) $g;
$h = (bool) $h;
$i = (bool) $i;
Cast to Array
$a = 5; // Integer
$b = 5.34; // Float
$c = "hello"; // String
$d = true; // Boolean
$e = NULL; // NULL
$a = (array) $a;
$b = (array) $b;
$c = (array) $c;
$d = (array) $d;
$e = (array) $e;
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}
$myCar = new Car("red", "Volvo");
$myCar = (array) $myCar;
var_dump($myCar);
Cast to Object
$a = 5; // Integer
$b = 5.34; // Float
$c = "hello"; // String
$d = true; // Boolean
$e = NULL; // NULL
$a = (object) $a;
$b = (object) $b;
$c = (object) $c;
$d = (object) $d;
$e = (object) $e;
$a = array("Volvo", "BMW", "Toyota"); // indexed array
$b = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); // associative array
$a = (object) $a;
$b = (object) $b;
Cast to NULL
$a = 5; // Integer
$b = 5.34; // Float
$c = "hello"; // String
$d = true; // Boolean
$e = NULL; // NULL
$a = NULL;
$b = NULL;
$c = NULL;
$d = NULL;
$e = NULL;
PHP Numbers
$a = 5;
$b = 5.34;
$c = "25";
var_dump($a);
var_dump($b);
var_dump($c);
The PHP is_int() Function
$x = 5985;
var_dump(is_int($x));
$y = 59.85;
var_dump(is_int($y));
The PHP is_float() Function
$x = 10.365;
var_dump(is_float($x));
PHP Infinity
$x = 1.9e411;
var_dump(is_infinite($x));
PHP NAN and is_nan() Function
$x = acos(8);
var_dump($x);
// Check if value is not a number (NaN)
var_dump(is_nan($x));
PHP Number and Numerical Strings
$x = 5985;
var_dump(is_numeric($x));
$x = "5985";
var_dump(is_numeric($x));
$x = "59.85" + 100;
var_dump(is_numeric($x));
$x = "Hello";
var_dump(is_numeric($x));
PHP Get The Integer Value of a Variable
$x = 23465.768;
echo intval($x);
echo "<br>";
$x = "23465.768";
echo intval($x);
PHP - Escape Characters PHP Escape Characters
$x = "We are the so-called "Vikings" from the north.";
echo $x;
$x = "We are the so-called \"Vikings\" from the north.";
echo $x;
Escape Characters \' Single Quote
<!DOCTYPE html>
<html>
<body>
<?php
$x = 'We are the so-called \'Vikings\' from the north.';
echo $x;
?>
</body>
</html>
We are the so-called 'Vikings' from the north.
We are the so-called "Vikings" from the north.
\" Double Quote \$ PHP variables \n New Line
<!DOCTYPE html>
<html>
<body>
<pre>
<?php
$x = "Hello\nWorld";
echo $x;
?>
</pre>
<p>To preserve any whitespace or line breaks, we have wrapped the result in a PRE element</p>
</body>
</html>
Hello
World
To preserve any whitespace or line breaks, we have wrapped the result in a PRE element.
\r Carriage Return \t Tab \f Form Feed \ooo Octal value
<!DOCTYPE html>
<html>
<body>
<p>A backslash followed by three integers will result in a octal value:</p>
<?php
$x = "\110\145\154\154\157";
echo $x;
?>
</body>
</html>
A backslash followed by three integers will result in a octal value:
Hello
\xhh Hex value
<!DOCTYPE html>
<html>
<body>
<p>A backslash followed by an 'x' and a hex number represents a hex value:</p>
<?php
$x = "\x48\x65\x6c\x6c\x6f";
echo $x;
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p>A backslash followed by an 'x' and a hex number represents a hex value:</p>
<?php
$x = "\x48\x65\x6c\x6c\x6f";
echo $x;
?>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p>A backslash followed by an 'x' and a hex number represents a hex value:</p>
<?php
$x = "\x48\x65\x6c\x6c\x6f";
echo $x;
?>
</body>
</html>
A backslash followed by an 'x' and a hex number represents a hex value:
Hello
PHP - Slicing Strings PHP substr() - Slice a String
$x = "Hello World!";
echo substr($x, 6, 5);
Slice String to the End
$x = "Hello World!";
echo substr($x, 6);
Slice String From the End
$x = "Hello World!";
echo substr($x, -5, 3);
Negative Length
$x = "Hi, how are you?";
echo substr($x, 5, -3);
PHP - Concatenate Strings String Concatenation
$x = "Hello";
$y = "World";
$z = $x . $y;
echo $z;
$x = "Hello";
$y = "World";
$z = $x . " " . $y;
echo $z;
$x = "Hello";
$y = "World";
$z = "$x $y";
echo $z;
PHP - Modify Strings PHP strtoupper() Function
$x = "Hello World!";
echo strtoupper($x);
PHP strtolower() Function
$x = "Hello World!";
echo strtolower($x);
PHP str_replace() Function
$x = "Hello World!";
echo str_replace("World", "Dolly", $x);
PHP strrev() Function
$x = "Hello World!";
echo strrev($x);
PHP trim() Function
$x = " Hello World! ";
echo trim($x);
PHP explode() Function
$x = "Hello lovely World!";
$y = explode(" ", $x);
//Use print_r() to display the result
print_r($y);
PHP String Functions PHP strlen() Function
echo strlen("Hello world!");
PHP str_word_count() Function
echo str_word_count("Hello world!");
PHP str_contains() Function
$txt = "I really love PHP!";
var_dump(str_contains($txt, "love"));
$txt = "I really love PHP!";
var_dump(str_contains($txt, "Love"));
PHP strpos() Function
echo strpos("Hello world!", "world");
PHP str_starts_with() Function
$txt = "I really love PHP!";
var_dump(str_starts_with($txt, "I really"));
$txt = "I really love PHP!";
var_dump(str_starts_with($txt, "i really"));
$txt = "I really love PHP!";
var_dump(str_ends_with($txt, "PHP!"));
$txt = "I really love PHP!";
var_dump(str_ends_with($txt, "php!"));
PHP Strings
echo "Hello";
echo 'Hello';
$x = "John";
echo "Hello $x"; // Returns Hello John
$x = "John";
echo 'Hello $x'; // Returns Hello $x
// Using double quotes
$x = "John";
echo "Hello $x\n";
echo "\tHow are you?\n";
// Using single quotes
$x = 'John';
echo 'Hello $x\n';
echo '\tHow are you?\n';
PHP Data Types Use var_dump() to Get the Data Type
$x = 5;
var_dump($x); // dumps int(5)
PHP String Data Type
$x = 'Hello world!';
var_dump($x);
PHP Int Data Type
$x = 5985;
var_dump($x);
PHP Float Data Type
$x = 10.365;
var_dump($x);
$x = true;
var_dump($x);
PHP Array Data Type
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
PHP Object Data Type
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function message() {
return "My car is a " . $this->color . " " . $this->model . "!";
}
}
$myCar = new Car("red", "Volvo");
var_dump($myCar);
PHP NULL Data Type
$x = "Hello world!";
$x = null;
var_dump($x);
Changing Data Type
$x = 5;
var_dump($x);
$x = "Hello";
var_dump($x);
$x = 5;
$x = (string) $x;
var_dump($x);
PHP echo and print Functions
echo "Hello";
echo("Hello");
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
echo "<h2>$txt1</h2>";
echo "<p>Study PHP at $txt2</p>";
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
echo '<h2>' . $txt1 . '</h2>';
echo '<p>Study PHP at ' . $txt2 . '</p>';
The PHP print Function
print "Hello";
print("Hello");
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
print "<h2>$txt1</h2>";
print "<p>Study PHP at $txt2</p>";
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
print '<h2>' . $txt1 . '</h2>';
print '<p>Study PHP at ' . $txt2 . '</p>';
PHP Variable Scope
$x = 5; // global scope
function myTest() {
// using x inside this function will not work
echo "Variable x inside function is: $x";
}
myTest();
echo "Variable x outside function is: $x";
function myTest() {
$x = 5; // local scope
echo "Variable x inside function is: $x";
}
myTest();
// using x outside the function will not work
echo "Variable x outside function is: $x";
function myTest() {
static $x = 0; // static scope
echo $x;
$x++;
}
myTest();
myTest();
myTest();
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
PHP Variables
$x = 5;
$y = "John";
$txt = "W3Schools.com";
echo "I love $txt!";
$txt = "W3Schools.com";
echo 'I love ' . $txt . '!';
$x = 5;
$y = 4;
echo $x + $y;
$x = 5; // $x is an integer
$y = "John"; // $y is a string
echo $x;
echo $y;
var_dump(5);
var_dump("John");
var_dump(3.14);
var_dump(true);
var_dump([2, 3, 56]);
var_dump(NULL);
$x = $y = $z = "Fruit";
PHP Multi-line Comments
/* The next statement will
print a welcome message */
echo 'Welcome Home!';
/*
echo 'Welcome to my home!';
echo 'Mi casa su casa!';
*/
echo 'Hello!';
$x = 5 /* + 15 */ + 5;
echo $x;
Comments in PHP
// This is a single-line comment
# This is also a single-line comment
/* This is a
multi-line
comment */
$d = dir(getcwd());
Kode `echo` di dalam file `php-dir-func.php` yang sedang Anda buka berfungsi untuk menampilkan informasi mengenai direktori aktif menggunakan objek direktori PHP (`dir()`).
Berikut adalah penjelasan baris per baris:
```php
$d = dir(getcwd());
- Baris ini membuat objek direktori (
$d) dengan mengambil path direktori saat ini menggunakan fungsigetcwd()(yaitu dari folder tempat script ini dijalankan:/home/anekakeb/public_html/edukasi/w3schools).
echo "Handle: " . $d->handle . "<br>";
$d->handle: Berfungsi untuk menampilkan stream handle (resource identifier) dari direktori yang sedang dibuka.
echo "Path: " . $d->path . "<br>";
$d->path: Berfungsi untuk menampilkan string path lengkap dari direktori yang sedang diakses saat ini.
while (($file = $d->read()) !== false){
echo "filename: " . $file . "<br>";
}
$d->read(): Berfungsi untuk membaca isi direktori satu per satu (baik file maupun folder di dalamnya, termasuk.dan..). Perulanganwhileini akan terus berjalan sampai seluruh isi direktori habis terbaca (!== false).- Di dalam perulangan, setiap nama file atau folder yang terbaca dicetak ke layar dengan awalan teks
filename:.
$d->close();
- Baris ini berfungsi untuk menutup handle direktori setelah selesai digunakan agar memori sistem kembali dilepaskan.
The ClassName::class Constant
This constant returns the class name and name of the namespace (if any):
myValue(); ?>
[hasil:](https://www.w3schools.com/php/phptryit.asp?filename=tryphp_const_classname)
The ClassName::class Constant This constant returns the class name and name of the namespace (if any):
myArea\Fruits
The __TRAIT__ Constant
This constant returns the trait name:
msg1(); ?>
[hasil:](https://www.w3schools.com/php/phptryit.asp?filename=tryphp_const_trait)
The TRAIT Constant This constant returns the trait name:
message1
The __NAMESPACE__ Constant
This constant returns the name of the namespace:
[hasil:](https://www.w3schools.com/php/phptryit.asp?filename=tryphp_const_namespace)
The NAMESPACE Constant This constant returns the name of the namespace:
myArea
The __LINE__ Constant
This constant returns the current line number:
hasil:
The LINE Constant This constant returns the current line number:
9
The __METHOD__ Constant
This constant returns both class and function name:
myValue(); ?>
hasil:
The METHOD Constant This constant returns both class and function name:
Fruits::myValue
The __FUNCTION__ Constant
This constant returns the function name:
hasil:
The FUNCTION Constant This constant returns the function name:
myMessage
The __FILE__ Constant
This constant returns the full path and the name of the file:
hasil:
The FILE Constant This constant returns the full path and the name of the file:
C:\awesomesites\w3schools\php\magic_const_file.php
PHP magic constant:
The __CLASS__ Constant
This constant returns the class name:
myValue(); ?>
hasil:
The CLASS Constant This constant returns the class name:
Fruits
The __DIR__ Constant
This constant returns the directory name of the file:
----
hasil: The DIR Constant This constant returns the directory name of the file:
C:\awesomesites\w3schools\php
---
apa perintah pengganti:
$rootPath = DIR;
agar bisa mundur 1 folder ke atas ?
Untuk mundur satu folder ke atas dari direktori file saat ini, Anda bisa menggunakan fungsi `dirname()` membungkus `__DIR__`.
Perintah penggantinya adalah:
```php
$rootPath = dirname(__DIR__);
Penjelasan:
__DIR__menghasilkan path direktori tempat file PHP tersebut berada saat ini.dirname($path)berfungsi untuk mengambil nama induk (folder di atasnya) dari path yang diberikan. Jika dibungkus seperti di atas, ia akan naik satu tingkat ke folder parent-nya.