មូលដ្ឋាន PHP: Arrays + Loops + Array Functions

រកៀន Array, Loop ជាមួយ Array និង Function សំខាន់ៗ

តម្រូវការមុន: ចេះ PHP syntax, variables, data types, operators, control structures, functions រួចហើយ

1. Indexed Arrays (អារេមានលេខរកាង)

គំនិត: បង្កើត និង ចូលប្រើ Indexed Array

Indexed Array រក្សាទុកតម្លៃច្រើនក្នុង variable មួយ។ ធាតុនីមួយៗមាន index ចាប់ពី 0។

  • បង្កើតដោយ [] ហើយនា array()
  • ចូលប្រើ: $arr[0], $arr[1]
<?php
$fruits = ["Apple", "Banana", "Mango", "Orange"];
echo $fruits[0]; // Apple (index 0)
echo $fruits[2]; // Mango (index 2)

// Update
$fruits[1] = "Strawberry";

// Add element
$fruits[] = "Grape";

echo count($fruits); // 5
?>

លទ្ធផល:

fruits[0] = Apple fruits[2] = Mango fruits[1] (updated) = Strawberry count = 5 All: Apple, Strawberry, Mango, Orange, Grape

គំនិត: បន្ថែម និង លុបធាតុ

ប្រើ array_push() បន្ថែមចុង, array_pop() លុបចុង, array_unshift() បន្ថែមដើម, array_shift() លុបដើម.

<?php
$colors = ["Red", "Green", "Blue"];
array_push($colors, "Yellow");    // Add to end
$removed = array_pop($colors);    // Remove from end
array_unshift($colors, "White");  // Add to start
$first = array_shift($colors);    // Remove from start
print_r($colors);
?>

លទ្ធផល:

មុន: [Red, Green, Blue] push(Yellow): [Red, Green, Blue, Yellow] pop(): [Red, Green, Blue] removed=Yellow unshift(White): [White, Red, Green, Blue] shift(): [Red, Green, Blue] removed=White

គំនិត: for vs foreach

មានពីរបប loop ដែលប្រើជាមួយ indexed array: for (ពេលត្រូវការ index) និង foreach (សាមញ្ញជាង).

<?php
$scores = [85, 92, 78, 65, 95];

// for loop
for ($i = 0; $i < count($scores); $i++) {
    echo "Index $i: $scores[$i]\n";
}

// foreach loop
foreach ($scores as $score) {
    echo "Score: $score\n";
}

// foreach with index
foreach ($scores as $index => $score) {
    echo "[$index] => $score\n";
}
?>

លទ្ធផល:

=== for loop === Index 0: 85 Index 1: 92 Index 2: 78 Index 3: 65 Index 4: 95 === foreach === Score: 85 Score: 92 Score: 78 Score: 65 Score: 95 === foreach with index === [0] => 85 [1] => 92 [2] => 78 [3] => 65 [4] => 95

ឆេការ: Indexed Arrays (6 លំហាត)

P1. (Multiple Choice) តើ index របស់ធាតុដំបូងក្នុង PHP array គឺប៉ុន្មាន?

a) 1   b) 0   c) -1   d) first

ជំនួយ: PHP array ចាប់រាប់ពី...

b) 0 - PHP indexed array ចាប់ពី index 0។

P2. បង្កើត array មាន 4 ពណ៌ ហើយ print ធាតុទី 3។

ជំនួយ: ធាតុទី 3 = index 2

$colors = ["Red", "Green", "Blue", "Yellow"];
echo $colors[2]; // Blue

P3. បន្ថែម "PHP" ទៅចុង array ["HTML","CSS","JS"] ដោយប្រើ 2 វិធី។

ជំនួយ: $arr[] = ... និង array_push()

$langs = ["HTML", "CSS", "JS"];
// Method 1:
$langs[] = "PHP";
// Method 2:
array_push($langs, "PHP");

P4. (Multiple Choice) count($arr) របស់ $arr = [10, 20, 30] គឺប៉ុន្មាន?

a) 2   b) 3   c) 30   d) 60

b) 3 - array មាន 3 ធាតុ។

P5. (Coding) ប្រើ for loop print គ្រប់ធាតុក្នុង $nums = [10,20,30,40,50]

ជំនួយ: ប្រើ count() សម្រាប់ loop condition

$nums = [10, 20, 30, 40, 50];
for ($i = 0; $i < count($nums); $i++) {
    echo $nums[$i] . "\n";
}

P6. (Coding) ប្រើ foreach គិតផលបូក $prices = [100,250,75,300]

ជំនួយ: $total = 0; បន្ទាប់បន្ថែមនីមួយៗក្នុង loop

$prices = [100, 250, 75, 300];
$total = 0;
foreach ($prices as $price) {
    $total += $price;
}
echo "Total: $total"; // 725

2. Associative Arrays (អារេជាគូរ)

គំនិត: Key-Value Pairs

Associative Array ប្រើ key (string) ជាជំនួសលេខរកាង។ key នីមួយៗជាប់គូរជាមួយ value មួយ។

<?php
$student = [
    "name"  => "Sokha",
    "age"   => 20,
    "major" => "IT",
    "score" => 85
];

echo $student["name"];  // Sokha
echo $student["score"]; // 85

// Update
$student["score"] = 90;

// Add new key
$student["email"] = "sokha@mail.com";
?>

លទ្ធផល:

name: Sokha score: 85 score (updated): 90 email (new): sokha@mail.com All keys: name, age, major, score, email

គំនិត: បង្ហាញជា Table

ប្រើ foreach($arr as $key => $value) ដើម្បី loop គូរ key-value និងបង្ហាញល្អ។

<?php
$product = ["name"=>"Laptop","price"=>850,"brand"=>"ASUS","stock"=>15];
foreach ($product as $key => $value) {
    echo "$key: $value\n";
}
?>

លទ្ធផល (table):

KeyValue
nameLaptop
price850
brandASUS
stock15

ឆេការ: Associative Arrays (5 លំហាត)

P7. បង្កើត associative array សម្រាប់សៀវពៅ (title, author, price, pages)។ Print title។

ជំនួយ: ប្រើ => ដើម្បីកំណត់ key-value

$book = ["title"=>"PHP Basics","author"=>"John","price"=>25,"pages"=>350];
echo $book["title"]; // PHP Basics

P8. (Multiple Choice) តើចូលប្រើ key "age" ក្នុង $person ដោយរបៀបណា?

a) $person[0]   b) $person["age"]   c) $person->age   d) $person.age

b) $person["age"] - ប្រើ key name ក្នុង []។

P9. (Coding) ប្រើ foreach print key-value របស់ $phone = ["brand"=>"Samsung","model"=>"Galaxy","price"=>300]

ជំនួយ: foreach($arr as $key => $value)

$phone = ["brand"=>"Samsung","model"=>"Galaxy","price"=>300];
foreach ($phone as $key => $value) {
    echo "$key: $value\n";
}

P10. (Coding) បន្ថែម key "color" = "Black" និងប្ដូរ "price" = 15000 ក្នុង $car

ជំនួយ: $arr["newkey"] = value

$car = ["brand"=>"Toyota","price"=>12000];
$car["color"] = "Black";
$car["price"] = 15000;
print_r($car);

P11. (Coding) ពិនិត្យថាតើ key "email" មានក្នុង $user ហើយនាទេ?

ជំនួយ: array_key_exists() ហើយនា isset()

$user = ["name"=>"Dara","age"=>21];
if (array_key_exists("email", $user)) {
    echo "Email exists";
} else {
    echo "No email key";
}

3. Multidimensional Arrays (អារេពហុជាន់)

គំនិត: Array of Arrays

Multidimensional array គឺជា array ក្នុង array។ ផ្តល់ជាមួយ nested foreach។

<?php
$students = [
    ["name"=>"Sokha",   "age"=>20, "score"=>85],
    ["name"=>"Dara",    "age"=>21, "score"=>92],
    ["name"=>"Vichetra","age"=>19, "score"=>78],
];
// Access:
echo $students[0]["name"];  // Sokha
echo $students[1]["score"]; // 92
?>

លទ្ធផល:

students[0]["name"] = Sokha students[1]["score"] = 92 students[2]["name"] = Vichetra

គំនិត: Nested foreach + Table

ប្រើ nested foreach ដើម្បី loop rows និង columns បង្ហាញជា table។

<?php
foreach ($students as $row) {
    echo "<tr>";
    foreach ($row as $key => $val) {
        echo "<td>$val</td>";
    }
    echo "</tr>";
}
?>

លទ្ធផល (rendered):

# Name Age Score Major
1 សុខា 20 85 IT
2 ដារា 21 92 IT
3 វិចិត្រា 19 78 Business
4 ចាន់ថន 22 65 English
5 នារី 20 95 IT
6 ពិសិដ្ឋ 21 45 Business

ឆេការ: Multidimensional Arrays (5 លំហាត)

P12. បង្កើត array របស់ 3 products (name, price, stock)។ Print price របស់ product ទី 2។

ជំនួយ: $products[1]["price"]

$products = [
    ["name"=>"Laptop","price"=>800,"stock"=>10],
    ["name"=>"Phone","price"=>500,"stock"=>25],
    ["name"=>"Tablet","price"=>300,"stock"=>15],
];
echo $products[1]["price"]; // 500

P13. (Coding) ប្រើ nested foreach បង្ហាញ students ជា HTML table។

ជំនួយ: Outer foreach = rows, Inner foreach = columns

echo "<table border='1'>";
foreach ($students as $student) {
    echo "<tr>";
    foreach ($student as $val) {
        echo "<td>$val</td>";
    }
    echo "</tr>";
}
echo "</table>";

P14. (Mini-Challenge) រក student ដែលមាន score ខ្ពស់បំផុត។

ជំនួយ: ប្រើ loop តាមដាន max score និង name

$maxScore = 0; $topStudent = "";
foreach ($students as $s) {
    if ($s["score"] > $maxScore) {
        $maxScore = $s["score"];
        $topStudent = $s["name"];
    }
}
echo "Top: $topStudent ($maxScore)";

P15. (Mini-Challenge) បង្ហាញតែ students ដែលជាប់ (score >= 50)។

ជំនួយ: ប្រើ if ក្នុង foreach

$passed = [];
foreach ($students as $s) {
    if ($s["score"] >= 50) {
        $passed[] = $s;
    }
}
foreach ($passed as $p) {
    echo $p["name"] . ": " . $p["score"] . "\n";
}

P16. (Coding) បន្ថែម student ថ្មីទៅ $students ហើយ print count។

ជំនួយ: $students[] = [...]

$students[] = ["name"=>"Bopha","age"=>19,"score"=>88,"major"=>"IT"];
echo "Total: " . count($students);

4. Loop ជាមួយ Arrays

គំនិត: for loop + Indexed Array

ប្រើ for ពេលត្រូវការ index។ ប្រើ count() សម្រាប់ condition។

<?php
$cities = ["Phnom Penh", "Siem Reap", "Battambang", "Sihanoukville"];
for ($i = 0; $i < count($cities); $i++) {
    echo ($i + 1) . ". " . $cities[$i] . "\n";
}
?>

លទ្ធផល:

1. Phnom Penh 2. Siem Reap 3. Battambang 4. Sihanoukville

គំនិត: foreach (Indexed + Associative)

foreach ជា loop ដែលប្រើជាងអតិបរមា។ ប្រើបានជាមួយ indexed និង associative array។

<?php
// Indexed
$fruits = ["Apple", "Banana", "Mango"];
foreach ($fruits as $fruit) {
    echo "Fruit: $fruit\n";
}
// Associative
$person = ["name"=>"Dara", "age"=>21, "city"=>"Phnom Penh"];
foreach ($person as $key => $value) {
    echo "$key: $value\n";
}
?>

លទ្ធផល:

=== Indexed === Fruit: Apple Fruit: Banana Fruit: Mango === Associative === name: Dara age: 21 city: Phnom Penh

គំនិត: Nested Loops (Multidimensional)

<?php
$matrix = [[1,2,3],[4,5,6],[7,8,9]];
foreach ($matrix as $rowIndex => $row) {
    echo "Row $rowIndex: ";
    foreach ($row as $val) {
        echo "$val ";
    }
    echo "\n";
}
?>

លទ្ធផល:

Row 0: 1 2 3 Row 1: 4 5 6 Row 2: 7 8 9

គំនិត: break និង continue

break បញ្ឈប់ loop។ continue លុបទៅជុមបន្ទាប់។

<?php
$scores = [85, 92, 45, 78, 30, 95, 60];

// continue: skip scores below 50
echo "Passing scores:\n";
foreach ($scores as $s) {
    if ($s < 50) continue;
    echo "$s ";
}

// break: stop at first failing score
echo "\nScores until first fail:\n";
foreach ($scores as $s) {
    if ($s < 50) break;
    echo "$s ";
}
?>

លទ្ធផល:

Passing (continue skips <50): 85 92 78 95 60 Until first fail (break at <50): 85 92

5. Array Functions សំខាន់ៗ

Group 1: Add / Remove

array_push | array_pop | array_shift | array_unshift
<?php
$arr = [10, 20, 30];
array_push($arr, 40);       // [10,20,30,40]
$last = array_pop($arr);    // [10,20,30] removed=40
array_unshift($arr, 5);     // [5,10,20,30]
$first = array_shift($arr); // [10,20,30] removed=5
?>

លទ្ធផល (មុន / ក្រោយ):

Start: [10,20,30] push(40): [10,20,30,40] pop(): [10,20,30] removed=40 unshift(5): [5,10,20,30] shift(): [10,20,30] removed=5

Group 2: Search

in_array | array_search
<?php
$fruits = ["Apple", "Banana", "Mango", "Orange"];
var_dump(in_array("Mango", $fruits));   // true
var_dump(in_array("Grape", $fruits));   // false
$pos = array_search("Orange", $fruits); // 3
?>

លទ្ធផល:

in_array('Mango'): bool(true) in_array('Grape'): bool(false) array_search('Orange'): index = 3

Group 3: Sort

sort | rsort | asort | ksort
<?php
$nums = [30, 10, 50, 20, 40];
sort($nums);   // [10,20,30,40,50]
rsort($nums);  // [50,40,30,20,10]

$ages = ["Sokha"=>20, "Dara"=>18, "Neary"=>22];
asort($ages);  // sort by value, keep keys
ksort($ages);  // sort by key
?>

លទ្ធផល (មុន / ក្រោយ):

មុន: [30,10,50,20,40] sort(): [10,20,30,40,50] rsort(): [50,40,30,20,10] មុន asort: Sokha=20 Dara=18 Neary=22 ក្រោយ asort: Dara=18 Sokha=20 Neary=22 ក្រោយ ksort: Dara=18 Neary=22 Sokha=20

Group 4: Transform / Utility

count | array_sum | array_unique | array_merge | array_keys | array_values | implode | explode
<?php
$nums = [10, 20, 30, 20, 10, 40];
echo count($nums);                  // 6
echo array_sum($nums);              // 130
print_r(array_unique($nums));       // [10,20,30,40]
print_r(array_merge([1,2],[3,4]));  // [1,2,3,4]

$p = ["name"=>"Dara","age"=>21];
print_r(array_keys($p));    // ["name","age"]
print_r(array_values($p));  // ["Dara",21]

echo implode(" - ", ["A","B","C"]); // A - B - C
$parts = explode(",", "PHP,JS,Python");
?>

លទ្ធផល:

count: 6 array_sum: 130 array_unique: [10,20,30,40] array_merge: [1,2,3,4] array_keys: [name,age] array_values: [Dara,21] implode(' - ',['A','B','C']): A - B - C explode(',','PHP,JS,Python'): [PHP,JS,Python]

ឆេការ: Array Functions (4 លំហាត)

P17. (Coding) ដាក់លំដាប់ $nums = [5,3,8,1,9,2] ពីតូចទៅធ ហើយ print។

ជំនួយ: sort() ប្ដូរ array ដោយផ្ទាល់

$nums = [5,3,8,1,9,2];
sort($nums);
echo implode(", ", $nums); // 1, 2, 3, 5, 8, 9

P18. (Coding) Merge: $frontend = ["HTML","CSS","JS"] និង $backend = ["PHP","MySQL"]

ជំនួយ: array_merge($a, $b)

$frontend = ["HTML","CSS","JS"];
$backend = ["PHP","MySQL"];
$all = array_merge($frontend, $backend);
echo implode(", ", $all);

P19. (Coding) លុបធាតុដដែលពី [1,2,3,2,4,1,5] ហើយគិតផលបូក។

ជំនួយ: array_unique() បន្ទាប់មក array_sum()

$arr = [1,2,3,2,4,1,5];
$unique = array_unique($arr);
$sum = array_sum($unique);
echo "Unique: ".implode(",",$unique)."\n";
echo "Sum: $sum"; // 15

P20. (Coding) ប្ដូរ string "apple,banana,mango" ជា array (explode) ហើយប្ដូរមកវិញជា string ដោយ " | " (implode)

ជំនួយ: explode(",", $str) + implode(" | ", $arr)

$str = "apple,banana,mango";
$arr = explode(",", $str);
$result = implode(" | ", $arr);
echo $result; // apple | banana | mango

Interactive Playground

Demo 1: Indexed Array Playground

បញ្ចូលតម្លៃដោយផ្ដាច់ដោយកម្មា (comma)

Demo 2: Student Profile (Associative Array)

Demo 3: Student Table (Multidimensional)

# Name Age Score Major Status
1 សុខា 20 85 IT Pass
2 ដារា 21 92 IT Pass
3 វិចិត្រា 19 78 Business Pass
4 ចាន់ថន 22 65 English Pass
5 នារី 20 95 IT Pass
6 ពិសិដ្ឋ 21 45 Business Fail
Total: 6
Avg: 76.7
Passed: 5
Max: 95

Demo 4: Array Functions Lab

ជ្រើសរើស function មួយដើម្បីបង្ហាញ មុន / ក្រោយ

Mini-Project: Student Score Manager

Challenge

ប្រើ $students array បង្កើត score report ពេញលេញ:

  • តារាង students + pass/fail
  • Average, Max, Min score
  • បញ្ជី passing students
  • រាប់ students ជាមួយ major
<?php
$students = [
    ["name"=>"Sokha","age"=>20,"score"=>85,"major"=>"IT"],
    ["name"=>"Dara","age"=>21,"score"=>92,"major"=>"IT"],
    ["name"=>"Vichetra","age"=>19,"score"=>78,"major"=>"Business"],
    ["name"=>"Chanthorn","age"=>22,"score"=>65,"major"=>"English"],
    ["name"=>"Neary","age"=>20,"score"=>95,"major"=>"IT"],
    ["name"=>"Piseth","age"=>21,"score"=>45,"major"=>"Business"],
];

$scores = array_column($students, "score");
$avg = round(array_sum($scores) / count($scores), 1);
$passed = array_filter($students, fn($s) => $s["score"] >= 50);

$majors = [];
foreach ($students as $s) {
    $m = $s["major"];
    if (!isset($majors[$m])) $majors[$m] = 0;
    $majors[$m]++;
}
?>

លទ្ធផល:

6
Total
76.7
Average
95
Highest
45
Lowest
5
Passed

Students per Major:

IT: 3 Business: 2 English: 1

បញ្ជី Passing Students (score >= 50):

  • សុខា - Score: 85 (IT)
  • ដារា - Score: 92 (IT)
  • វិចិត្រា - Score: 78 (Business)
  • ចាន់ថន - Score: 65 (English)
  • នារី - Score: 95 (IT)

ចម្លៃយត្រូវ (Answer Key)

Indexed Arrays (P1-P6)

P1: b) 0

P2: $colors = ["Red","Green","Blue","Yellow"]; echo $colors[2];

P3: $langs[] = "PHP"; ហើយនា array_push($langs, "PHP");

P4: b) 3

P5: for($i=0; $i<count($nums); $i++) echo $nums[$i]."\n";

P6: $total=0; foreach($prices as $p) $total+=$p; echo $total;

Associative Arrays (P7-P11)

P7: $book=["title"=>"PHP Basics",...]; echo $book["title"];

P8: b) $person["age"]

P9: foreach($phone as $key=>$value) echo "$key: $value\n";

P10: $car["color"]="Black"; $car["price"]=15000;

P11: if(array_key_exists("email",$user)) / isset($user["email"])

Multidimensional Arrays (P12-P16)

P12: echo $products[1]["price"]; // 500

P13: Nested foreach: outer=rows, inner=columns

P14: Track $maxScore និង $topStudent ក្នុង foreach

P15: if($s["score"]>=50) ក្នុង foreach ដើម្បី filter

P16: $students[] = [...]; echo count($students);

Array Functions (P17-P20)

P17: sort($nums); echo implode(", ",$nums);

P18: $all = array_merge($frontend,$backend);

P19: $unique=array_unique($arr); $sum=array_sum($unique);

P20: $arr=explode(",",$str); $result=implode(" | ",$arr);