Click on a topic to expand and learn in detail.
PHP is a server-side scripting language used to build dynamic websites.
<?php
echo "Hello World";
?>
$name = "Alice";
$age = 25;
// Data types: string, int, float, bool, array, object, null
// Arithmetic: +, -, *, /, %
$sum = 5 + 3;
// Comparison: ==, !=, >, <
$result = (5 > 3);
// Logical: &&, ||, !
$flag = true && false;
$age = 18;
if($age >= 18){
echo "Adult";
}else{
echo "Minor";
}
switch($age){
case 18:
echo "Exactly 18";
break;
default:
echo "Other";
}
// for loop
for($i=0; $i<5; $i++){
echo $i;
}
// while loop
$i=0;
while($i<5){
echo $i;
$i++;
}
// do-while loop
$j=0;
do{
echo $j;
$j++;
}while($j<5);
// foreach (arrays)
$fruits = array("Apple","Banana","Mango");
foreach($fruits as $fruit){
echo $fruit;
}
function greet($name){
return "Hello ".$name;
}
echo greet("Alice");
// Anonymous function
$add = function($a,$b){ return $a+$b; };
echo $add(5,3);
$fruits = array("Apple","Banana","Mango");
echo $fruits[0]; // Apple
// Associative array
$person = array("name"=>"Alice","age"=>25);
echo $person["name"];
$text = "Hello World";
echo strtoupper($text); // HELLO WORLD
echo strtolower($text); // hello world
echo str_replace("World","PHP",$text); // Hello PHP
<form method="post" action="process.php">
Name: <input type="text" name="name">
<input type="submit">
</form>
<?php
$name = $_POST['name'];
echo "Hello ".$name;
?>
<?php
// Write to file
$file = fopen("data.txt","w");
fwrite($file,"Hello PHP");
fclose($file);
// Read file
$file = fopen("data.txt","r");
echo fread($file,filesize("data.txt"));
fclose($file);
?>
<?php
$host = "localhost";
$db = "test";
$user = "root";
$pass = "";
// Using PDO
try{
$conn = new PDO("mysql:host=$host;dbname=$db",$user,$pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected Successfully";
}catch(PDOException $e){
echo "Connection failed: ".$e->getMessage();
}
?>