<?php
/* ---------------- ARRAYS ---------------- */
// Indexed Array
$fruits = ["Apple", "Banana", "Mango"];
echo $fruits[0] . "<br>";
// Associative Array
$user = ["name" => "Tanishq", "age" => 21];
echo $user["name"] . "<br>";
// Multidimensional Array
$students = [["John", 90], ["Aman", 85]];
echo $students[0][0] . "<br>";
// Array Merge
$a = ["Red", "Green"];
$b = ["Blue", "Yellow"];
$merged = array_merge($a, $b);
print_r($merged);
echo "<br><br>";
/* ---------------- FILE OPERATIONS ---------------- */
$filename = "demo.txt";
// file_exists()
echo file_exists($filename) ? "File exists<br>" : "File not found<br>";
// fopen() + fwrite()
$file = fopen($filename, "w");
fwrite($file, "Hello PHP!");
fclose($file);
// fopen() + fread()
$file = fopen($filename, "r");
echo fread($file, filesize($filename)) . "<br>";
fclose($file);
// unlink() // delete file if needed
// unlink($filename);
/* ---------------- FILE UPLOAD ---------------- */
// HTML form needed:
// <form method="POST" enctype="multipart/form-data"><input type="file" name="myfile"><button>Upload</button></form>
if ($_FILES) {
if ($_FILES["myfile"]["error"] == 0) {
move_uploaded_file($_FILES["myfile"]["tmp_name"], "uploads/" . $_FILES["myfile"]["name"]);
echo "File uploaded!<br>";
}
}
/* ---------------- DIRECTORY OPERATIONS ---------------- */
$dir = "myfolder";
// Check directory exists
if (!is_dir($dir)) {
mkdir($dir); // create directory
echo "Directory created<br>";
} else {
echo "Directory exists<br>";
}
// Reading directory using scandir()
$files = scandir($dir);
echo "scandir(): ";
print_r($files);
echo "<br>";
// Reading directory using opendir()
if ($handle = opendir($dir)) {
echo "Files inside using opendir(): ";
while (($file = readdir($handle)) !== false) {
echo $file . " ";
}
closedir($handle);
echo "<br>";
}
// Delete directory (only if empty)
// rmdir($dir);
?>
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter