ตัวแปลภาษา PHP ออนไลน์ - รันและทดสอบโค้ด PHP ได้ทันที
เขียน, รัน, และทดสอบโค้ด PHP ได้ทันทีด้วยตัวแปลภาษา PHP ออนไลน์ฟรีของเรา ไม่ต้องดาวน์โหลดหรือติดตั้ง — แค่เปิดเบราว์เซอร์แล้วเริ่มเขียนโค้ดใน PHP ได้เลย
💡 คู่มือพื้นฐาน PHP สำหรับผู้เริ่มต้น
1. การประกาศตัวแปรและค่าคงที่
ตัวแปร PHP เริ่มต้นด้วย $
. ใช้ define()
หรือ const
สำหรับค่าคงที่
$x = 10;
$pi = 3.14;
$name = "Alice";
$isActive = true;
define("MAX_USERS", 100);
const APP_NAME = "CodeUtility";
2. เงื่อนไข (if / switch)
ใช้ if
, elseif
, และ else
สำหรับการแยกสาขา หรือ switch
สำหรับหลายกรณี
$x = 2;
if ($x == 1) {
echo "One\n";
} elseif ($x == 2) {
echo "Two\n";
} else {
echo "Other\n";
}
switch ($x) {
case 1:
echo "One\n";
break;
case 2:
echo "Two\n";
break;
default:
echo "Other\n";
}
3. ลูป
PHP รองรับลูป for
, while
, และ foreach
for ($i = 0; $i < 3; $i++) {
echo $i . "\n";
}
$n = 3;
while ($n > 0) {
echo $n . "\n";
$n--;
}
4. อาเรย์
อาเรย์เก็บค่าหลายค่า PHP รองรับอาเรย์แบบมีดัชนีและแบบเชื่อมโยง
$nums = array(10, 20, 30);
echo $nums[1];
5. การจัดการอาเรย์
ใช้ฟังก์ชันอย่าง array_push()
, array_pop()
, count()
, และการตัดด้วย array_slice()
$fruits = ["apple", "banana"];
array_push($fruits, "cherry");
array_pop($fruits);
print_r($fruits);
$sliced = array_slice($fruits, 0, 1);
print_r($sliced);
6. การรับ/ส่งข้อมูลผ่านคอนโซล
ใช้ readline()
สำหรับการรับข้อมูล CLI และ echo
/print
สำหรับการส่งออก
$name = readline("Enter your name: ");
echo "Hello, $name\n";
PHP Basics Guide
7. ฟังก์ชัน
ฟังก์ชันรวบรวมตรรกะที่ใช้ซ้ำได้ พารามิเตอร์สามารถมีค่าเริ่มต้นได้
function greet($name = "Guest") {
return "Hello, $name";
}
echo greet("Alice");
8. อาเรย์เชื่อมโยง
อาเรย์ PHP สามารถทำงานเหมือนพจนานุกรมที่มีคีย์เป็นสตริง
$person = ["name" => "Bob", "age" => 25];
echo $person["name"];
9. การจัดการข้อยกเว้น
ใช้ try
, catch
, และ throw
เพื่อจัดการข้อผิดพลาด
try {
throw new Exception("Something went wrong");
} catch (Exception $e) {
echo $e->getMessage();
}
10. การรับ/ส่งข้อมูลไฟล์
ใช้ฟังก์ชันอย่าง fopen()
, fwrite()
, และ fread()
สำหรับการทำงานกับไฟล์
$file = fopen("test.txt", "w");
fwrite($file, "Hello File");
fclose($file);
$file = fopen("test.txt", "r");
echo fread($file, filesize("test.txt"));
fclose($file);
11. การจัดการสตริง
ใช้ฟังก์ชันอย่าง strlen()
, str_replace()
, และ explode()
$text = "Hello World";
echo strlen($text);
echo str_replace("Hello", "Hi", $text);
print_r(explode(" ", $text));
12. คลาสและออบเจ็กต์
ใช้คลาสเพื่อจำลองวัตถุในโลกจริงและตรรกะที่ใช้ซ้ำได้
class Person {
public $name;
function __construct($name) {
$this->name = $name;
}
function greet() {
return "Hi, I'm " . $this->name;
}
}
$p = new Person("Alice");
echo $p->greet();
13. การอ้างอิง
ใน PHP คุณสามารถส่งตัวแปรโดยการอ้างอิงโดยใช้ &
function addOne(&$num) {
$num++;
}
$x = 5;
addOne($x);
echo $x; // 6