Chapterبەش 7 · Lectureوانە 7.2
Arrays in PHPڕیزەکەکان لە PHPـدا
An array keeps many values under one name. Learn indexed and associative arrays: how to create them, read and change elements, count and print them, loop over them with foreach, follow the rules for keys, and use array elements inside strings.
چەندین لەژێر یەک ناودا هەڵدەگرێت. فێری و ببە: چۆن دروستیان بکەیت، بخوێنیتەوە و بگۆڕیت، بیانژمێریت و چاپیان بکەیت، بە foreach بەناویاندا بخولێیتەوە، یاساکانی بزانیت و لەناو بەکاربهێنیت.
What you will learnچی فێر دەبیت
- Explain what an array is and name the three kinds of arrays in PHP.
- Create indexed arrays with
array(), with[]and by assigning to indexes. - Create associative arrays with
=>and know the rules for keys. - Read, change and add elements, and count them with
count(). - Show a whole array with
print_r()orvar_dump(), and explain whyechoprints "Array". - Loop over arrays with
foreach(value, and key => value) and withfor+count(). - Put array elements inside double-quoted strings safely.
- Use
max(),min(),array_sum()andend().
- ڕوونی بکەیتەوە چییە و سێ جۆرەکەی لە PHPـدا ناو ببەیت.
- بە
array()، بە[]و بە دانانی بۆ دروست بکەیت. - بە
=>دروست بکەیت و یاساکانی بزانیت. - بخوێنیتەوە، بگۆڕیت و زیادیان بکەیت و بە
count()بیانژمێریت. - هەموو بە
print_r()یانvar_dump()پیشان بدەیت و ڕوونی بکەیتەوە بۆچیecho«Array» چاپ دەکات. - بە
foreach( و key => value) و بەfor+count()بەناو بخولێیتەوە. - بە سەلامەتی لەناو دابنێیت.
max()،min()،array_sum()وend()بەکاربهێنیت.
Why do we need arrays?بۆچی ڕیزەکەکانمان پێویستە؟
Until now, one has held one , for example $name = "Aram";. But real programs work with lists: all the students in a class, all the prices in a shop, all the marks of one student. If you want to store 100 numbers, you would need 100 different variable names.
تا ئێستا هەر یەک هەڵگرتووە، بۆ نموونە $name = "Aram";. بەڵام ڕاستەقینە لەگەڵ لیست کار دەکەن: هەموو خوێندکارانی پۆلێک، نرخی هەموو کاڵاکانی دوکانێک، هەموو نمرەکانی خوێندکارێک. ئەگەر بتەوێت 100 ژمارە هەڵبگریت، پێویستت بە 100 ناوی جیاواز دەبێت بۆ .
An array solves this problem. It is a special variable that stores many values under one name. Each value sits in its own numbered or named place inside the array.
ئەم کێشەیە چارەسەر دەکات. تایبەتە کە چەندین لەژێر یەک ناودا هەڵدەگرێت. هەر لە شوێنێکی تایبەتی خۆیدا دادەنرێت، کە ژمارە یان ناوێکی هەیە.
A collection of values in one variable, each found by its (or ). In Java and C# an array has a fixed length and one element type (String[] names = new String[2];); PHP's array grows and can also use names as keys. Python uses a instead.
کۆکراوەیەکی نرخەکانە لە یەک گۆڕاودا، هەر نرخێک بە (یان ) دەدۆزرێتەوە. لە Java و C#ـدا درێژییەکی جێگیر و یەک جۆری دانەی هەیە (String[] names = new String[2];)؛ ڕیزەکی PHP گەورە دەبێت و دەتوانێت ناویش وەک کلیل بەکار بهێنێت. Python لەبری ئەوە بەکار دەهێنێت.
<?php
// Without an array: one variable for every value
$student1 = "Aram";
$student2 = "Shilan";
$student3 = "Karwan";
// With an array: one variable holds all the values
$students = ["Aram", "Shilan", "Karwan"];
echo $students[1];Shilan
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2-4
Without an array, every student needs a separate variable.
بەبێ ، هەر خوێندکارێک جیای پێویستە.
- Lineدێڕی 7
With an array, one variable
$studentsholds all three names.بە ، یەک واتە
$studentsهەر سێ ناوەکە هەڵدەگرێت.- Lineدێڕی 9
[1]picks the second name, because counting starts at 0.[1]ناوی دووەم هەڵدەبژێرێت، چونکە ژماردن لە 0ەوە دەست پێدەکات.
In Kurdish: what an array is, why we use arrays, and what we can do with them in PHP.
بە کوردی: چییە، بۆچی بەکاردەهێنین و لە چییان پێ دەکەین.
Kurdish (Sorani) introduction to arrays
ناساندنی بە کوردیی سۆرانی.
Why do we need arrays?بۆچی ڕیزەکەکانمان پێویستە؟
Like a row of mailboxesوەک ڕیزێک سندوقی پۆست
An array is like a row of numbered mailboxes at the post office. The whole row has one name (the array variable). Each box has its own number (the index) and holds one thing (the value). To get a letter, you only need the row name and the box number.
وەک کۆمەڵێک سندوقی پۆستی ژمارەدار وایە کە لە پۆستخانەدا لە تەنیشت یەکەوە دانراون. هەموو کۆمەڵەکە یەک ناوی هەیە (ناوی ). هەر سندوقێک ژمارەی تایبەتی خۆی هەیە () و یەک شت هەڵدەگرێت (). بۆ وەرگرتنی نامەیەک تەنها ناوی کۆمەڵەکە و ژمارەی سندوقەکەت پێویستە.
Where the analogy stops workingسنووری ئەم نموونەیە
Real mailboxes have a fixed number of boxes. A PHP array grows and shrinks when you add or remove values, and one box can even hold another whole row of boxes (a multidimensional array).
سندوقی پۆستی ڕاستەقینە ژمارەیەکی دیاریکراوی هەیە. بەڵام PHP گەورە و بچووک دەبێتەوە کاتێک زیاد یان کەم دەکەیت و تەنانەت سندوقێک دەتوانێت کۆمەڵێکی تەواوی سندوقی تر لەخۆ بگرێت ().
Why do we need arrays?بۆچی ڕیزەکەکانمان پێویستە؟
The three kinds of arraysسێ جۆرەکەی ڕیزەک
PHP has three kinds of arrays:
لە PHPـدا سێ جۆر هەیە:
- Indexed array (also called a numeric array): an array with a numeric index. You find each value by its number: 0, 1, 2 …
- Associative array (also called a hash): an array with named keys. Each key is associated with a value, so you find each value by its name.
- Multidimensional array: an array containing one or more arrays, for example a table with rows and columns.
- : کە ژمارەن. هەر بە ژمارەکەی دەدۆزیتەوە: 0، 1، 2 …
- : کە ناون. هەر بە بەستراوە، بۆیە هەر بە ناوەکەی دەدۆزیتەوە.
- : کە یەک یان چەند تری تێدایە، بۆ نموونە خشتەیەک بە و .
<?php
// 1. Indexed array: each value has a number (0, 1, 2 ...)
$cities = ["Erbil", "Slemani", "Duhok"];
// 2. Associative array: each value has a name (a key)
$student = ["name" => "Aram", "stage" => 4, "mark" => 90];
// 3. Multidimensional array: an array that holds other arrays
$marks = [
[90, 85, 77],
[68, 92, 81],
];
echo $cities[0] . "<br>";
echo $student["name"] . "<br>";
echo $marks[1][2];Erbil Aram 81
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
Erbil<br>Aram<br>81Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
Indexed: PHP gives the indexes 0, 1, 2 automatically.
ژمارەدار: PHP خۆی 0، 1، 2 دادەنێت.
- Lineدێڕی 6
Associative: you choose the keys
"name","stage"and"mark".پەیوەندیدار: خۆت
"name"،"stage"و"mark"هەڵدەبژێریت.- Lineدێڕی 9-12
Multidimensional: each element of
$marksis itself an array (a row of marks).فرەڕەهەند: هەر
$marksخۆی ( نمرە).- Lineدێڕی 16
Two pairs of brackets: first the row
[1], then the column[2].دوو جووت کەوانەی چوارگۆشە: سەرەتا
[1]، پاشان[2].
This lecture teaches indexed and associative arrays. Multidimensional arrays have their own lecture: Multidimensional arrays. Sorting arrays is in Sorting arrays.
ئەم وانەیە و فێر دەکات. وانەی تایبەتی خۆیان هەیە: ڕیزەکە فرەڕەهەندەکان. لە وانەی ڕیزکردنی ڕیزەکەکاندایە.
Indexed arraysڕیزەکە ژمارەدارەکان
An indexed array (a numerically indexed array, or simply numeric array) finds its values by number. These arrays can store numbers, strings and any other value, but their index is always a number. By default the index starts from zero.
خۆی بە ژمارە دەدۆزێتەوە. دەتوانن ژمارە، و هەر تر هەڵبگرن، بەڵام هەمیشە ژمارەیە. بە شێوەی بنەڕەتی لە سفرەوە دەست پێدەکات.
An whose keys are numbers, given automatically from 0: $colors = ["red", "green"];. It is also called a numeric array.
بریتییە لە کە ژمارەن و خۆکارانە لە سفرەوە دەدرێن: $colors = ["red", "green"];. پێی دەگوترێت ڕیزەکی ژمارەییش.
Indexed arraysڕیزەکە ژمارەدارەکان
Creating an indexed array with array()دروستکردنی ڕیزەکێکی ژمارەدار بە array()
Create an indexed array with the language construct array. Put the values between the round brackets, separated by commas:
بە array دروست بکە، کە . لەنێوان کەوانە ئاساییەکاندا دابنێ و بە کۆما لێکیان جیا بکەرەوە:
$array_name = array(values);Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
values stands for your own values, separated by commas.
values واتە خۆت، کە بە کۆما لێک جیا دەکرێنەوە.
PHP gives the keys automatically: 0, 1, 2 and so on. The first value gets index 0, the second gets index 1, and so on. Writing array() with nothing inside creates an empty array.
PHP خۆی بە شێوەی خۆکار دادەنێت: 0، 1، 2 و هتد. یەکەم 0 وەردەگرێت، دووەم 1 و بەم شێوەیە. نووسینی array() بەبێ هیچ شتێک لەناویدا بەتاڵ دروست دەکات.
<?php
$products = array('Tires', 'Oil', 'Spark Plugs');
$list = array(2, 4, 6, 8);
$empty = array(); // an empty array
echo "<pre>";
print_r($products);
print_r($list);
print_r($empty);
echo "</pre>";Array
(
[0] => Tires
[1] => Oil
[2] => Spark Plugs
)
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
)
Array
(
)HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<pre>Array
(
[0] => Tires
[1] => Oil
[2] => Spark Plugs
)
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
)
Array
(
)
</pre>Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Three strings. Their keys are 0, 1 and 2.
سێ . 0، 1 و 2ن.
- Lineدێڕی 3
Four numbers. Their keys are 0, 1, 2 and 3.
چوار ژمارە. 0، 1، 2 و 3ن.
- Lineدێڕی 4
array()with nothing inside: an empty array.array()بەبێ هیچ شتێک: بەتاڵ.- Lineدێڕی 6-10
print_r()shows every key and value;<pre>keeps its line breaks in the browser (explained below).print_r()هەموو و پیشان دەدات؛<pre>دێڕەکانی لە دەپارێزێت (لە خوارەوە ڕوون کراوەتەوە).
Indexed arraysڕیزەکە ژمارەدارەکان
The short syntax: [ ]شێوازی کورت: [ ]
Since PHP 5.4 you can write square brackets [ ] instead of array( ). Both create exactly the same array. $a = []; is the same as $a = array();. The short form is the modern, most common style; this course uses both, so learn to read both.
لە PHP 5.4ـەوە دەتوانیت کەوانەی چوارگۆشە [ ] لە جیاتی array( ) بنووسیت. هەردووکیان ڕێک هەمان دروست دەکەن. $a = []; وەک $a = array(); وایە. شێوازە کورتەکە شێوازی نوێ و باوترە؛ ئەم کۆرسە هەردووکیان بەکار دەهێنێت، بۆیە فێری خوێندنەوەی هەردووکیان ببە.
<?php
$products = ['Tires', 'Oil', 'Spark Plugs']; // the same as array('Tires', 'Oil', 'Spark Plugs')
$empty = []; // the same as array()
echo $products[2];Spark Plugs
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Square brackets create the same indexed array as
array(...).کەوانەی چوارگۆشە هەمان دروست دەکات کە
array(...)دروستی دەکات.- Lineدێڕی 3
[]alone is an empty array.[]بە تەنها بەتاڵە.- Lineدێڕی 5
Index 2 is the third value.
2 سێیەم .
Indexed arraysڕیزەکە ژمارەدارەکان
Giving indexes automatically or by handدانانی ئیندێکسەکان بە خۆکاری یان بە دەست
There are two ways to create an indexed array:
دوو ڕێگا هەیە بۆ دروستکردنی :
- The index can be assigned automatically. PHP numbers the values for you, starting at 0. This is what
array(1, 2, 3, 4, 5)does. - The index can be assigned manually. You choose the number for each value yourself:
$numeric[0] = "one";,$numeric[1] = "two";…
- دەتوانرێت بە خۆکاری دابنرێت. PHP خۆی ژمارە دەکات، لە 0ەوە. ئەمە ئەو کارەیە کە
array(1, 2, 3, 4, 5)دەیکات. - دەتوانرێت بە دەست دابنرێت. خۆت ژمارەی هەر هەڵدەبژێریت:
$numeric[0] = "one";،$numeric[1] = "two";…
Indexed arraysڕیزەکە ژمارەدارەکان
Lab 4, Example 6: both methodsتاقیگەی 4، نموونەی 6: هەردوو ڕێگاکە
Lab 4 (Example 6) shows both methods. Each array is printed with a foreach loop, which is explained below.
تاقیگەی 4 (نموونەی 6) هەردوو ڕێگاکە پیشان دەدات. هەر بە چاپ دەکرێت، کە لە خوارەوە ڕوون کراوەتەوە.
<?php
/* First method to create array. */
$numbers = array(1, 2, 3, 4, 5);
foreach ($numbers as $value) {
echo "Value is $value <br />";
}Value is 1 Value is 2 Value is 3 Value is 4 Value is 5
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
Value is 1 <br />Value is 2 <br />Value is 3 <br />Value is 4 <br />Value is 5 <br />Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
PHP gives the indexes 0 to 4 automatically.
PHP خۆی 0 تا 4 دادەنێت.
- Lineدێڕی 5
Inside double quotes
$valueis replaced by its value.<br />is an HTML line break.لەناو جووتەگوتەدا
$valueبە دەگۆڕدرێت.<br />دێڕشکێنی HTMLـە.
<?php
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
foreach ($numbers as $value) {
echo "Value is $value <br />";
}Value is one Value is two Value is three Value is four Value is five
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
Value is one <br />Value is two <br />Value is three <br />Value is four <br />Value is five <br />Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3-7
Each line puts one value at the index you choose. The first line also creates the array.
هەر دێڕێک یەک لەو دادەنێت کە هەڵیدەبژێریت. یەکەم دێڕ دروست دەکات.
Indexed arraysڕیزەکە ژمارەدارەکان
Creating by assigning, and adding at the endدروستکردن بە دانانی نرخ و زیادکردن لە کۆتاییدا
Notice in the second method that $numbers was never created with array() or []. When you assign to an index of a variable that does not exist yet, PHP creates the array automatically. It still is a good habit to write $a = []; first: it shows the reader that an array starts here, and it makes sure you do not add values to an old array by mistake.
لە ڕێگای دووەمدا سەرنج بدە کە $numbers هەرگیز بە array() یان [] دروست نەکراوە. کاتێک دەدەیتە کە هێشتا بوونی نییە، PHP بە خۆکاری دروست دەکات. لەگەڵ ئەوەشدا باشترە سەرەتا $a = []; بنووسیت: بە خوێنەر پیشان دەدات کە لێرەوە دەست پێدەکات و دڵنیات دەکاتەوە کە بەبێ ئەوەی بزانیت ناخەیتە سەر کۆن.
Empty square brackets $a[] = … add a value at the end of the array. PHP chooses the next free index for you.
کەوانەی چوارگۆشەی بەتاڵ $a[] = … دەخاتە کۆتایی . PHP خۆی یەکەم بەتاڵ بۆت هەڵدەبژێرێت.
<?php
$a = []; // start with an empty array (a good habit)
$a[0] = "Aram";
$a[1] = "Shilan";
echo $a[1] . "<br>";
// Without "$b = [];" PHP still creates the array:
$b[0] = "Karwan";
$b[1] = "Dilan";
echo $b[0] . "<br>";
// Empty brackets add a value at the end (the next free index)
$a[] = "Rezan";
echo $a[2];Shilan Karwan Rezan
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
Shilan<br>Karwan<br>RezanExplain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2-4
Start with an empty array, then assign index 0 and index 1.
بە بەتاڵ دەست پێبکە، پاشان 0 و 1 پڕ بکەرەوە.
- Lineدێڕی 8-9
$bdid not exist. The first assignment creates it as an array.$bبوونی نەبوو. یەکەم دانانی وەک دروستی دەکات.- Lineدێڕی 13
$a[]adds "Rezan" at the next free index, which is 2.$a[]ناوی "Rezan" لە یەکەم بەتاڵدا دادەنێت، کە 2ـە.
Indexed arraysڕیزەکە ژمارەدارەکان
Reading and changing one elementخوێندنەوە و گۆڕینی یەک دانە
To use one element, write the array name and then the index in square brackets: $array[index]. To print just one element, use echo $array[index]; with a real number in place of index.
بۆ بەکارهێنانی یەک ، ناوی بنووسە و پاشان لەناو کەوانەی چوارگۆشەدا: $array[index]. بۆ چاپکردنی تەنها یەک ، echo $array[index]; بەکاربهێنە و ژمارەیەکی ڕاستەقینە لە جیاتی index بنووسە.
<?php
$provinces = ["Erbil", "Slemani", "Duhok", "Halabja"];
echo $provinces[0] . "<br>"; // the first element: index 0
echo $provinces[3] . "<br>"; // the fourth element: index 3
$marks = [70, 85, 90];
$marks[0] = 75; // change the first mark
echo $marks[0];Erbil Halabja 75
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
Erbil<br>Halabja<br>75Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
Index 0 is the first element.
0 یەکەم .
- Lineدێڕی 5
Index 3 is the fourth element, because counting starts at 0.
3 چوارەم ، چونکە ژماردن لە 0ەوە دەست پێدەکات.
- Lineدێڕی 8
Assigning to an existing index replaces the old value.
دانانی بۆ هەبوو، دەگۆڕێت.
If you ask for an index that does not exist, PHP prints a warning and gives null (nothing is printed for it):
ئەگەر داوای بکەیت کە بوونی نییە، PHP پیشان دەدات و null دەداتەوە (هیچ شتێک بۆی چاپ ناکرێت):
<?php
$provinces = ["Erbil", "Slemani", "Duhok", "Halabja"];
echo $provinces[4]; // there is no index 4Warning: Undefined array key 4 in C:\xampp\htdocs\arrays\index.php on line 3
The file path in the message shows where your file is saved, so it will be different on your computer.
فایلەکە لەناو پەیامەکەدا شوێنی پاشەکەوتکردنی فایلەکەت پیشان دەدات، بۆیە لەسەر کۆمپیوتەرەکەی تۆ جیاواز دەبێت.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
The array has 4 elements, so the indexes are 0 to 3. Index 4 does not exist.
4 هەیە، بۆیە 0 تا 3ن. 4 بوونی نییە.
Looking inside an array: echo, print_r() and var_dump()سەیرکردنی ناو ڕیزەکێک: echo، print_r() و var_dump()
echo can print strings and numbers, but it cannot print an array. When you echo an array, PHP turns the array into the word Array and also shows a warning. This happens for every array, even an empty one.
echo دەتوانێت و ژمارە چاپ بکات، بەڵام ناتوانێت چاپ بکات. کاتێک بە echo چاپ دەکەیت، PHP دەگۆڕێت بۆ وشەی Array و پیشان دەدات. ئەمە بۆ هەموو ڕوودەدات، تەنانەت بەتاڵیش.
Looking inside an array: echo, print_r() and var_dump()سەیرکردنی ناو ڕیزەکێک: echo، print_r() و var_dump()
print_r() and var_dump()print_r() و var_dump()
To look inside an array, use one of these two built-in functions:
بۆ سەیرکردنی ناو ، یەکێک لەم دوو ئامادەیە بەکاربهێنە:
print_r($array)prints every key and value in a form people can read ("print readable"). It is the quickest way to check an array.var_dump($array)prints more detail: the number of elements, and the type and length of every value (string(3) "red"). Use it when you need to know exact types.
print_r($array)هەموو و بە شێوەیەک چاپ دەکات کە مرۆڤ بتوانێت بیخوێنێتەوە. خێراترین ڕێگایە بۆ پشکنینی .var_dump($array)وردەکاریی زیاتر چاپ دەکات: ژمارەی و جۆر و درێژیی هەموو (string(3) "red"). کاتێک پێویستت بە زانینی جۆری ورد هەیە بەکاری بهێنە.
print_r() و var_dump()PHPRuns on the serverلەسەر ڕاژەکاری وێب کار دەکات<?php
$array_name = array();
$colors = array("red", "green");
echo "<pre>";
print_r($array_name);
print_r($colors);
var_dump($array_name);
var_dump($colors);
echo "</pre>";Array
(
)
Array
(
[0] => red
[1] => green
)
array(0) {
}
array(2) {
[0]=>
string(3) "red"
[1]=>
string(5) "green"
}HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<pre>Array
(
)
Array
(
[0] => red
[1] => green
)
array(0) {
}
array(2) {
[0]=>
string(3) "red"
[1]=>
string(5) "green"
}
</pre>Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 6
An empty array:
print_rshowsArrayand two empty brackets.بەتاڵ:
print_rوشەیArrayو دوو کەوانەی بەتاڵ پیشان دەدات.- Lineدێڕی 7
Each element appears as
[key] => value.هەر بە شێوەی
[key] => valueدەردەکەوێت.- Lineدێڕی 8
array(0)means "an array with 0 elements".array(0)واتە « بە 0 ».- Lineدێڕی 9
string(3) "red": a string, 3 characters long.string(3) "red": ، 3 پیت درێژ.
| Toolئامراز | What it shows for an arrayبۆ چی پیشان دەدات | Use it forبۆ چی بەکاری بهێنیت |
|---|---|---|
echo $a; | Only the word Array, plus a warningتەنها وشەی Array، لەگەڵ | Never for whole arrays; use it for one element: echo $a[0];هەرگیز بۆ هەموو ؛ بۆ یەک بەکاری بهێنە: echo $a[0]; |
print_r($a); | Every key and valueهەموو و | Quick checks while you write codeپشکنینی خێرا لە کاتی نووسینی کۆددا |
var_dump($a); | Keys, values, types and lengths، ، جۆرەکان و درێژییەکان | Finding type problems ("5" or 5?)دۆزینەوەی کێشەی جۆر ("5" یان 5؟) |
Counting and looping over an indexed arrayژماردن و خولاندنەوە بەناو ڕیزەکێکی ژمارەداردا
To print all the elements of an array, we need a loop that goes through the elements one by one. PHP gives two common ways: the foreach loop and the for loop together with count().
بۆ چاپکردنی هەموو ، پێویستمان بە هەیە کە یەک بە یەک بە بڕوات. PHP دوو ڕێگای باو دەدات: و لەگەڵ count().
Counting and looping over an indexed arrayژماردن و خولاندنەوە بەناو ڕیزەکێکی ژمارەداردا
count(): how many elements?count(): چەند دانە؟
count($array) is a built-in function. It returns the number of elements in the array: 0 for an empty array, 3 for an array of three values.
count($array) . ژمارەی ناو دەگەڕێنێتەوە: 0 بۆ بەتاڵ، 3 بۆ سێ .
Counting and looping over an indexed arrayژماردن و خولاندنەوە بەناو ڕیزەکێکی ژمارەداردا
The foreach loopخولی foreach
foreach was made for arrays. It runs its code once for each element, from the first to the last, and each time it puts the current value into a variable you name after as:
foreach بۆ دروست کراوە. کۆدەکەی بۆ هەر جارێک جێبەجێ دەکات، لە یەکەمەوە تا دوایین و هەر جارێک ئێستا دەخاتە ناو ئەو کە دوای as ناوی دەنێیت:
foreach ($array as $value) {
code to run for each element;
}Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 1
Read it as: "for each element in
$array, put its value in$value". You choose the name$value($car,$name…).وا بیخوێنەوە: «بۆ هەر لە
$arrayدا، بخە ناو$value». ناوی$valueخۆت هەڵدەبژێریت ($car،$name…).
<?php
$cars = array("BMW", "NISSAN", "JAGUAR", "TOYOTA");
foreach ($cars as $value) {
echo $value;
}BMWNISSANJAGUARTOYOTA
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
Each turn of the loop,
$valueholds the next car name.لە هەر ،
$valueناوی ئۆتۆمبێلی دواتر هەڵدەگرێت.- Lineدێڕی 4
Nothing is printed between the names, so they run together.
هیچ شتێک لەنێوان ناوەکاندا چاپ ناکرێت، بۆیە پێکەوە دەلکێن.
echo adds nothing between values, so the names run together. Print a separator such as "<br>" after each value:
echo هیچ شتێک لەنێوان زیاد ناکات، بۆیە ناوەکان پێکەوە دەلکێن. دوای هەر جیاکەرەوەیەک وەک "<br>" چاپ بکە:
<?php
$cars = array("BMW", "NISSAN", "JAGUAR", "TOYOTA");
foreach ($cars as $value) {
echo $value . "<br>";
}BMW NISSAN JAGUAR TOYOTA
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
BMW<br>NISSAN<br>JAGUAR<br>TOYOTA<br>Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
Concatenate
"<br>"after each value."<br>"دوای هەر پێوە بلکێنە.
Counting and looping over an indexed arrayژماردن و خولاندنەوە بەناو ڕیزەکێکی ژمارەداردا
The for loop with count()خولی for لەگەڵ count()
You can also print every element with a for loop. count() tells the loop how many elements there are, and the loop counter is used as the index:
دەتوانیت هەموو بە چاپ بکەیت. count() بە دەڵێت چەند هەیە و وەک بەکاردێت:
for و count()PHPRuns on the serverلەسەر ڕاژەکاری وێب کار دەکات<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for ($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}Volvo BMW Toyota
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
Volvo<br>BMW<br>Toyota<br>Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
count($cars)is 3. It is saved in$arrlengthso it is not counted again on every turn.count($cars)دەکاتە 3. لە$arrlengthدا هەڵدەگیرێت بۆ ئەوەی لە هەموو دووبارە نەژمێردرێتەوە.- Lineدێڕی 4
$xtakes the values 0, 1, 2. The condition is<(less than), not<=.$x0، 1، 2 وەردەگرێت.<ـە (کەمتر)، نەک<=.- Lineدێڕی 5
$cars[$x]uses the counter as the index.$cars[$x]وەک بەکاردەهێنێت.
The condition must be $x < $arrlength. With <= the loop would also run for $x = 3 and ask for $cars[3], which does not exist: PHP prints Warning: Undefined array key 3. The summary version writes $x < count($cars) directly in the condition; that also works, but count() then runs on every turn.
دەبێت $x < $arrlength بێت. بە <= بۆ $x = 3یش جێبەجێ دەبێت و داوای $cars[3] دەکات، کە بوونی نییە: PHP Warning: Undefined array key 3 چاپ دەکات. وەشانی کورتەکە ڕاستەوخۆ $x < count($cars) لە دەنووسێت؛ ئەویش کار دەکات، بەڵام ئەو کاتە count() لە هەموو جێبەجێ دەبێت.
| Pointخاڵ | foreach | for + count() + count() |
|---|---|---|
| Needs indexes?پێویستی بە هەیە؟ | No. It visits every element by itself.نەخێر. خۆی بە هەموو دەڕوات. | Yes. Indexes must be 0, 1, 2 … with no gaps.بەڵێ. دەبێت 0، 1، 2 … بن بەبێ کەلێن. |
| Works for associative arrays?بۆ کار دەکات؟ | Yes (see key => value).بەڵێ (بڕوانە key => value). | No: their keys are not 0, 1, 2.نەخێر: 0، 1، 2 نین. |
| Risk of off-by-one mistakesمەترسیی | Noneنییە | Yes, if you write <= instead of <بەڵێ، ئەگەر لە جیاتی < بنووسیت <= |
| Best forباشترینە بۆ | Reading every element (most cases)خوێندنەوەی هەموو (زۆربەی کات) | When you need the position number, or every second elementکاتێک ژمارەی شوێنت پێویستە، یان دەتەوێت لە هەر دوو تەنها یەکێکیان بخوێنیتەوە |
Associative arraysڕیزەکە پەیوەندیدارەکان
Associative arrays work very much like numeric arrays, but their index is different: it is a string (a name) instead of a number. This index is called a key. Each key is associated with a value, which is where the name comes from. You find values by their name, not by their position. Another name for an associative array is a hash.
لە کارکردندا زۆر لە دەچن، بەڵام جیاوازە: لە جیاتی ژمارە (ناوێکە). ئەم پێی دەوترێت . هەر بە بەستراوە، ناوەکەش لێرەوە هاتووە. بە ناوەکانیان دەدۆزیتەوە، نەک بە شوێنیان. ناوێکی تری hashـە.
A collection that finds each value by a named instead of a position number: PHP's associative array ["Aram" => 22, "Hana" => 19], Dart's Map and Python's work this way. Each element is a .
کۆکراوەیەکە کە هەر نرخێک بە ناونراو دەدۆزێتەوە لە جیاتی ژمارەی شوێن: پەیوەندیداری PHP ["Aram" => 22, "Hana" => 19]، Mapـی Dart و Python بەم شێوەیە کار دەکەن. هەر دانەیەکی بریتییە لە .
In a student's own notes, the word associative is explained with Kurdish words that mean "attached", "related" and "linked": each element is made of two connected parts, a key and a value, and the key is the "key" (klil) that opens the value.
لە تێبینییەکانی خوێندکارێکدا، وشەی associative بە وشەی کوردیی وەک «پێوەبەستراو»، «پەیوەندی» و «بەستراو» ڕوون کراوەتەوە: هەر لە دوو بەشی بەیەکەوە بەستراو پێک دێت، و و ئەو کلیلەیە کە دەکاتەوە.
An associative array is like the price board in a bazaar shop. Each line has a name ("Tea", "Sugar", "Rice") and a price next to it. You never ask the shopkeeper for "item number 2"; you ask for the price of sugar. The name is the key, the price is the value.
وەک تەختەی نرخی دوکانێکی بازاڕ وایە. هەر دێڕێک ناوێکی هەیە («چا»، «شەکر»، «برنج») و نرخێک لە تەنیشتیەوە. هەرگیز لە دوکاندار ناپرسیت «کاڵای ژمارە 2 بە چەندە؟»؛ دەپرسیت شەکر بە چەندە. ناوی کاڵاکە و نرخەکەی .
Where the analogy stops workingسنووری ئەم نموونەیە
On a price board two lines can have the same name. In a PHP array each key is unique: writing the same key again replaces the old value (see duplicate keys).
لەسەر تەختەی نرخ دەکرێت دوو دێڕ هەمان ناویان هەبێت. لە PHPـدا هەر تاکە: نووسینەوەی هەمان دەگۆڕێت (بڕوانە کلیلەکانی دووبارە).
Associative arraysڕیزەکە پەیوەندیدارەکان
Creating an associative arrayدروستکردنی ڕیزەکێکی پەیوەندیدار
Create an associative array with array() (or [ ]) and write each element as key => value. The => sign means: this key points to this value.
بە array() (یان [ ]) دروست بکە و هەر بە شێوەی key => value بنووسە. نیشانەی => واتە: ئەم بەم بەستراوە.
<?php
$prices = array('Tires' => 100, 'Oil' => 10, 'Spark Plugs' => 4);
echo "<pre>";
print_r($prices);
echo "</pre>";
echo $prices['Oil'];Array
(
[Tires] => 100
[Oil] => 10
[Spark Plugs] => 4
)
10HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<pre>Array
(
[Tires] => 100
[Oil] => 10
[Spark Plugs] => 4
)
</pre>10Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Three key–value pairs:
'Tires' => 100,'Oil' => 10,'Spark Plugs' => 4.سێ :
'Tires' => 100،'Oil' => 10،'Spark Plugs' => 4.- Lineدێڕی 7
Read a value by its key.
بە بخوێنەوە.
The deck shows the same idea with a student record:
سلایدەکان هەمان بیرۆکە بە زانیاریی خوێندکارێک پیشان دەدەن:
<?php
$associative = array("name" => "Ahmad",
"stage" => 4,
"mark" => 90);
echo $associative["name"] . " is in stage " . $associative["stage"];
echo " and his mark is " . $associative["mark"] . ".";Ahmad is in stage 4 and his mark is 90.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2-4
The keys
"name","stage"and"mark"describe what each value means."name"،"stage"و"mark"ڕوون دەکەنەوە کە هەر چ واتایەکی هەیە.- Lineدێڕی 3
Values can be different types: a string and two integers.
دەتوانن جۆری جیاوازیان هەبێت: و دوو .
"name" | "stage" | "mark" |
|---|---|---|
Ahmad | 4 | 90 |
Associative arraysڕیزەکە پەیوەندیدارەکان
Second way: one key at a timeڕێگای دووەم: هەر جارە یەک کلیل
You can also create an associative array by assigning a value to a key of an array that does not exist yet. PHP creates the array on the first line:
هەروەها دەتوانیت دروست بکەیت بە دانانی بۆ کە هێشتا بوونی نییە. PHP لە یەکەم دێڕدا دروست دەکات:
<?php
$prices = []; // start empty (a good habit)
$prices['Tires'] = 100;
$prices['Oil'] = 10;
$prices['Spark Plugs'] = 4;
echo "<pre>";
print_r($prices);
echo "</pre>";Array
(
[Tires] => 100
[Oil] => 10
[Spark Plugs] => 4
)HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<pre>Array
(
[Tires] => 100
[Oil] => 10
[Spark Plugs] => 4
)
</pre>Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Optional but recommended: start with an empty array.
ئارەزوومەندانەیە بەڵام باشە: بە بەتاڵ دەست پێبکە.
- Lineدێڕی 3-5
Each line adds one key–value pair. The result is the same as
array('Tires' => 100, …).هەر دێڕێک یەک زیاد دەکات. ئەنجامەکە وەک
array('Tires' => 100, …)وایە.
Associative arraysڕیزەکە پەیوەندیدارەکان
Reading a value by its keyخوێندنەوەی نرخێک بە کلیلەکەی
Write the array name and the key in square brackets. String keys can use single or double quotes: $prices['Tires'] and $prices["Tires"] give the same value.
ناوی و لەناو کەوانەی چوارگۆشەدا بنووسە. دەتوانن گوتەی تاک یان جووت بەکاربهێنن: $prices['Tires'] و $prices["Tires"] هەمان دەدەن.
<?php
$prices = ['Tires' => 100, 'Oil' => 10];
echo $prices['Tires'] . "<br>"; // 100
echo $prices["Tires"] . "<br>"; // 100: the same element
$prices['Oil'] = 12; // change a value by its key
echo $prices['Oil'];100 100 12
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
100<br>100<br>12Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4-5
Both lines read the same element.
هەردوو دێڕەکە هەمان دەخوێننەوە.
- Lineدێڕی 6
Assigning to an existing key replaces its value.
دانانی بۆ هەبوو دەگۆڕێت.
Associative arraysڕیزەکە پەیوەندیدارەکان
foreach with key => valueforeach لەگەڵ key => value
With an associative array you usually want the keys too, not only the values. Give foreach two variables, joined by =>: the first receives the key, the second receives the value.
لەگەڵ زۆرجار دەوێت، نەک تەنها . دوو بدە بە foreach، کە بە => بەیەکەوە بەستراون: یەکەم وەردەگرێت، دووەم .
foreach ($array as $key => $value) {
code that can use $key and $value;
}<?php
$prices = ['Tea' => 1000, 'Sugar' => 2500, 'Rice' => 3000];
foreach ($prices as $item => $price) {
echo "$item costs $price dinars<br>";
}Tea costs 1000 dinars Sugar costs 2500 dinars Rice costs 3000 dinars
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
Tea costs 1000 dinars<br>Sugar costs 2500 dinars<br>Rice costs 3000 dinars<br>Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
$itemgets the key ("Tea", "Sugar", "Rice") and$pricegets the value.$itemوەردەگرێت ("Tea"، "Sugar"، "Rice") و$price.- Lineدێڕی 5
Both variables can be used inside the loop.
هەردوو دەتوانرێن لەناو بەکاربهێنرێن.
If you give foreach only one variable, you get only the values; the keys are not available inside the loop:
ئەگەر تەنها یەک بدەیت بە foreach، تەنها وەردەگریت؛ لەناو بەردەست نین:
<?php
$prices = ['Tea' => 1000, 'Sugar' => 2500, 'Rice' => 3000];
foreach ($prices as $price) {
echo $price . "<br>"; // only the values; the keys are not available
}1000 2500 3000
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
1000<br>2500<br>3000<br>Rules for keysیاساکانی کلیلەکان
Every element of a PHP array has a key. Indexed arrays use integer keys, associative arrays use string keys, and one array can even use both. This section collects the exact rules.
هەموو PHP هەیە. بەکاردەهێنن، و یەک تەنانەت دەتوانێت هەردووکیان بەکاربهێنێت. ئەم بەشە یاسا وردەکان کۆ دەکاتەوە.
What happens when two elements share a key, and how PHP chooses the next automatic key when only some elements have keys.
چی ڕوو دەدات کاتێک دوو هەمان هەبێت و چۆن خۆکاری دواتر دیاری دەکات کاتێک تەنها هەندێک هەیە.
Watch 10:02–12:05: duplicate keys and automatic indexing
لە 10:02 تا 12:05 سەیر بکە: دووبارە و خۆکار.
Rules for keysیاساکانی کلیلەکان
Keys can be integers or strings, nothing elseکلیلەکان دەتوانن ژمارەی تەواو یان زنجیرەنووسە بن، هیچی تر
A note in the course materials asks: "In PHP, can the keys in associative arrays be strings or numbers?" and answers "YESSSS". That is right, with one important detail: a key can only be an integer or a string. Other types are converted (cast) to one of these two:
تێبینییەک لە کەرەستەکانی کۆرسەکەدا دەپرسێت: «لە PHPـدا، دەکرێت یان ژمارە بن؟» و دەڵێت «YESSSS». ئەمە ڕاستە، بەڵام وردەکارییەکی گرنگی هەیە: تەنها دەتوانێت یان بێت. جۆرەکانی تر دەگۆڕدرێن () بۆ یەکێک لەم دووانە:
<?php
$array = [
"name" => "John",
"age" => 25,
42 => "forty-two",
3.14 => "pi",
];
echo $array["name"]; // Output: John
echo $array["age"]; // Output: 25
echo $array[42]; // Output: forty-two
echo $array[3.14]; // Output: piDeprecated: Implicit conversion from float 3.14 to int loses precision in C:\xampp\htdocs\arrays\index.php on line 6 John25forty-two Deprecated: Implicit conversion from float 3.14 to int loses precision in C:\xampp\htdocs\arrays\index.php on line 12 pi
The file path in the message shows where your file is saved, so it will be different on your computer.
فایلەکە لەناو پەیامەکەدا شوێنی پاشەکەوتکردنی فایلەکەت پیشان دەدات، بۆیە لەسەر کۆمپیوتەرەکەی تۆ جیاواز دەبێت.
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 6
3.14is a float. PHP cuts it to the integer3and shows a Deprecated message (PHP 8.1 and newer).3.14. PHP دەیبڕێت بۆ3و پەیامی Deprecated پیشان دەدات (PHP 8.1 و نوێتر).- Lineدێڕی 12
Reading
$array[3.14]is also converted to$array[3], so "pi" is found, with a second message.خوێندنەوەی
$array[3.14]یش دەگۆڕدرێت بۆ$array[3]، بۆیە "pi" دەدۆزرێتەوە، لەگەڵ پەیامێکی دووەم.
The note's comments say every line simply prints its value. The values are printed, but the key 3.14 was never stored: it became 3, and PHP marks this as deprecated (still working, but no longer recommended). Look at the real keys:
تێبینییەکە دەڵێن هەموو دێڕێک بە سادەیی چاپ دەکات. چاپ دەکرێن، بەڵام 3.14 هەرگیز هەڵنەگیرا: بوو بە 3 و PHP ئەمە بە دیاری دەکات (هێشتا کار دەکات، بەڵام ئیتر پێشنیار ناکرێت). سەیری ڕاستەقینە بکە:
<?php
$array = ["name" => "John", "age" => 25, 42 => "forty-two", 3 => "pi"];
echo $array[3] . "<br>";
echo implode(", ", array_keys($array));pi name, age, 42, 3
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
pi<br>name, age, 42, 3Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
array_keys()returns all keys of an array;implode()joins them with ", ".array_keys()هەموو دەگەڕێنێتەوە؛implode()بە ", " پێکەوەیان دەلکێنێت.
| Key you write نووسراو | Key PHP stores هەڵگیراو لەلایەن PHP | Whyبۆچی |
|---|---|---|
42 | 42 | An integer stays an integer. وەک خۆی دەمێنێتەوە. |
"42" | 42 | A string that is a normal whole number becomes an integer. کە ژمارەیەکی تەواوی ئاسایی بێت دەبێتە . |
"07" | "07" | A leading zero: not a normal integer, so it stays a string.سفری سەرەتا: ژمارەیەکی تەواوی ئاسایی نییە، بۆیە وەک دەمێنێتەوە. |
"1.5" | "1.5" | A decimal in a string stays a string.ژمارەی دەیی لەناو وەک دەمێنێتەوە. |
3.14 | 3 | A float is cut to an integer (Deprecated since PHP 8.1). دەبڕدرێت بۆ (Deprecated لە PHP 8.1ـەوە). |
true / false | 1 / 0 | Booleans become 1 and 0. دەبنە 1 و 0. |
null | "" | Becomes the empty string (Deprecated in PHP 8.5).دەبێتە بەتاڵ (Deprecated لە PHP 8.5ـدا). |
<?php
$array = [
"name" => "Aram",
42 => "forty-two",
"7" => "seven", // the string "7" becomes the integer key 7
"07" => "zero seven", // "07" stays a string key
true => "yes", // true becomes the integer key 1
];
echo $array[7] . "<br>";
echo $array["07"] . "<br>";
echo $array[1] . "<br>";
echo "<pre>";
var_dump(array_keys($array));
echo "</pre>";seven
zero seven
yes
array(5) {
[0]=>
string(4) "name"
[1]=>
int(42)
[2]=>
int(7)
[3]=>
string(2) "07"
[4]=>
int(1)
}HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
seven<br>zero seven<br>yes<br><pre>array(5) {
[0]=>
string(4) "name"
[1]=>
int(42)
[2]=>
int(7)
[3]=>
string(2) "07"
[4]=>
int(1)
}
</pre>Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
"7"is stored as the integer 7, so$array[7]finds it."7"وەک 7 هەڵدەگیرێت، بۆیە$array[7]دەیدۆزێتەوە.- Lineدێڕی 5
"07"stays the string"07"."07"وەک"07"دەمێنێتەوە.- Lineدێڕی 6
trueis stored as the integer 1.trueوەک 1 هەڵدەگیرێت.- Lineدێڕی 14
var_dump()shows the type of each key:intorstring.var_dump()جۆری هەر پیشان دەدات:intیانstring.
Rules for keysیاساکانی کلیلەکان
Mixing your keys with automatic keysتێکەڵکردنی کلیلەکانی خۆت لەگەڵ کلیلەکانی خۆکار
Inside array() you may give a key to some elements and leave it out for others. An element without a key gets an automatic integer key. After string keys only, the numbering starts from 0:
لەناو array()دا دەتوانیت بۆ هەندێک دابنێیت و بۆ هەندێکی تر نا. کە نەبێت خۆکار وەردەگرێت. دوای تەنها ، ژمارەکردن لە 0ەوە دەست پێدەکات:
<?php
$team = array('GK' => "Karwan", 'FW' => "Rezan", 'Soran', 'Dilan');
echo "<pre>";
print_r($team);
echo "</pre>";Array
(
[GK] => Karwan
[FW] => Rezan
[0] => Soran
[1] => Dilan
)HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
<pre>Array
(
[GK] => Karwan
[FW] => Rezan
[0] => Soran
[1] => Dilan
)
</pre>Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
'GK'(goalkeeper) and'FW'(forward) are keys you chose.'Soran'and'Dilan'have no key.'GK'(گۆڵپارێز) و'FW'(هێرشبەر) خۆتن.'Soran'و'Dilan'نییە.- Lineدێڕی 5
Soran gets index 0 and Dilan gets index 1.
Soran 0 وەردەگرێت و Dilan 1.
Rules for keysیاساکانی کلیلەکان
The rule: the largest integer key + 1یاساکە: گەورەترین کلیلی ژمارەی تەواو + 1
"Starting from 0" is only true when no integer key exists yet. The full rule is: the next automatic key is the largest integer key used so far, plus 1 (or 0 if there is none). A student tested this with an array that starts with the key 8:
«لە 0ەوە دەست پێدەکات» تەنها کاتێک ڕاستە کە هێشتا هیچ نەبێت. یاسا تەواوەکە ئەمەیە: خۆکاری داهاتوو گەورەترین بەکارهاتوو تا ئێستا، زائیدەی 1ـە (یان 0 ئەگەر هیچ نەبێت). خوێندکارێک ئەمەی بە تاقی کردەوە کە بە 8 دەست پێدەکات:
<?php
$mixed = array(8 => "Hana", 'TR' => "Soran", "Dilan", "Rezan");
echo $mixed[10] . "<br>"; # Rezan
echo $mixed[8] . "<br>"; # Hana
echo $mixed[9] . "<br>"; # Dilan
echo $mixed['TR']; # Soran
echo "<pre>";
print_r($mixed);
echo "</pre>";Rezan
Hana
Dilan
Soran
Array
(
[8] => Hana
[TR] => Soran
[9] => Dilan
[10] => Rezan
)HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
Rezan<br>Hana<br>Dilan<br>Soran<pre>Array
(
[8] => Hana
[TR] => Soran
[9] => Dilan
[10] => Rezan
)
</pre>Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Key 8 is given;
'TR'is a string key; the last two values get no key.8 دراوە؛
'TR'؛ دوو کۆتایی وەرناگرن.- Lineدێڕی 3-6
The
#comments show what each line prints. The source printed them with no separator;"<br>"is added here.#پیشان دەدەن هەر دێڕێک چی چاپ دەکات. کۆدە ڕەسەنەکە بێ جیاکەرەوە چاپی کردبوون؛ لێرەدا"<br>"زیاد کراوە.
Integer and string keys can also be mixed one by one, as in this student test: $a['A'] uses a string key and $a[1] an integer key in the same array. (How "$a[A]" works inside a string is explained in the next section.)
و دەتوانرێن یەک بە یەکیش تێکەڵ بکرێن، وەک لەم تاقیکردنەوەیەی خوێندکارێکدا: $a['A'] و $a[1] لە هەمان بەکاردەهێنن. (چۆنیەتی کارکردنی "$a[A]" لەناو لە بەشی داهاتوودا ڕوون کراوەتەوە.)
<?php
$a['A'] = "Aram";
$a[1] = "Shilan";
echo "$a[A]";
echo "<br />";
echo "$a[1]";Aram Shilan
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
Aram<br />ShilanRules for keysیاساکانی کلیلەکان
Each key is uniqueهەر کلیلێک تاکە
An array cannot hold the same key twice. If you write a key again, the new value replaces the old one, and the number of elements does not grow:
ناتوانێت هەمان دوو جار هەڵبگرێت. ئەگەر دووبارە بنووسیتەوە، دەگۆڕێت و ژمارەی زیاد نابێت:
<?php
$colors = ["sky" => "blue", "grass" => "green", "sky" => "grey"];
echo $colors["sky"] . "<br>"; // grey: the second "sky" replaced the first
echo count($colors); // 2 elements, not 3grey 2
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
grey<br>2Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
"sky"appears twice. Only the last value, "grey", is kept."sky"دوو جار هاتووە. تەنها دوایین ، "grey"، دەمێنێتەوە.
Array elements inside stringsدانەکانی ڕیزەک لەناو زنجیرەنووسەکاندا
You often want to print an element as part of a sentence. Inside a double-quoted string, PHP replaces variables with their values (this is called interpolation). Array elements need special care here. There are three correct ways:
زۆرجار دەتەوێت وەک بەشێک لە دەقێک چاپ بکەیت. لەناو دا، PHP بە دەگۆڕێت (ئەمە پێی دەوترێت ). لێرەدا ئاگاداریی تایبەتیان دەوێت. سێ ڕێگای دروست هەیە:
- Concatenation. Do not rely on interpolation; join the pieces with
.:"The price for tires is " . $prices['Tires']. Remember the space before the closing quote. - Simple interpolation, without quotes around the key:
"The price for tires is $prices[Tires]". Inside a string only, the key is written without quotes. - Curly braces (recommended):
"The price for tires is {$prices['Tires']}". Inside{ }you write the element exactly as in normal code, quotes included. This also works for keys with spaces and for multidimensional arrays.
- . پشت بە مەبەستە؛ پارچەکان بە
.پێکەوە بلکێنە:"The price for tires is " . $prices['Tires']. پێش گوتەی داخستن لەبیر مەکە. - سادە، بەبێ گوتە لە دەوری :
"The price for tires is $prices[Tires]". تەنها لەناو ، بەبێ گوتە دەنووسرێت. - کەوانەی لوول (پێشنیارکراو):
"The price for tires is {$prices['Tires']}". لەناو{ }دا ڕێک وەک کۆدی ئاسایی دەنووسیت، گوتەکانیشەوە. ئەمە بۆ بۆشاییدار و کار دەکات.
<?php
$prices = ['Tires' => 100, 'Oil' => 10, 'Spark Plugs' => 4];
// 1. Concatenation (note the space before the closing quote)
echo "The price for tires is " . $prices['Tires'] . "<br>";
// 2. Simple interpolation: NO quotes around the key
echo "The price for tires is $prices[Tires]<br>";
// 3. Curly braces: quotes are allowed (recommended)
echo "The price for tires is {$prices['Tires']}<br>";
echo "Spark plugs cost {$prices['Spark Plugs']}";The price for tires is 100 The price for tires is 100 The price for tires is 100 Spark plugs cost 4
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
The price for tires is 100<br>The price for tires is 100<br>The price for tires is 100<br>Spark plugs cost 4Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5
Concatenation: the string ends with a space, then
.joins the value.: بە کۆتایی دێت، پاشان
.پێوە دەلکێنێت.- Lineدێڕی 8
Simple interpolation:
$prices[Tires]with no quotes, only inside double quotes.سادە:
$prices[Tires]بەبێ گوتە، تەنها لەناو جووتەگوتەدا.- Lineدێڕی 11
Curly-brace syntax: quotes allowed. This is the clearest form.
شێوازی کەوانەی لوول: گوتە ڕێگەپێدراوە. ئەمە ڕوونترین شێوەیە.
- Lineدێڕی 12
A key with a space (
Spark Plugs) only works with curly braces or concatenation.بە (
Spark Plugs) تەنها بە کەوانەی لوول یان کار دەکات.
Array elements inside stringsدانەکانی ڕیزەک لەناو زنجیرەنووسەکاندا
What goes wrongچی تێک دەچێت
1. Writing quotes around the key in simple interpolation is a parse error:
1. نووسینی گوتە لە دەوری لە سادەدا :
<?php
$prices = ['Tires' => 100, 'Oil' => 10, 'Spark Plugs' => 4];
echo "The price for tires is $prices['Tires']";Parse error: syntax error, unexpected string content "", expecting "-" or identifier or variable or number in C:\xampp\htdocs\arrays\index.php on line 3
2. Leaving the quotes out outside a string is a fatal error in PHP 8. PHP thinks Tires is the name of a constant:
2. لابردنی گوتەکان لە دەرەوەی لە PHP 8دا . PHP وا دەزانێت Tires ناوی :
<?php
$prices = ['Tires' => 100, 'Oil' => 10, 'Spark Plugs' => 4];
echo $prices[Tires];Fatal error: Uncaught Error: Undefined constant "Tires" in C:\xampp\htdocs\arrays\index.php:3
Stack trace:
#0 {main}
thrown in C:\xampp\htdocs\arrays\index.php on line 33. Forgetting the space in concatenation glues the words together:
3. لەبیرچوونی لە وشەکان بەیەکەوە دەلکێنێت:
<?php
$prices = ['Tires' => 100, 'Oil' => 10, 'Spark Plugs' => 4];
echo "The price for tires is". $prices['Tires'];The price for tires is100
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
There is no space after "is", so the output is "is100".
دوای "is" نییە، بۆیە "is100"ـە.
| You writeدەنووسیت | Inside "…"لەناو "…" | Outside a stringلە دەرەوەی |
|---|---|---|
$prices['Tires'] | Parse error | Correctدروستە |
$prices[Tires] | Correct (simple syntax)دروستە (شێوازی سادە) | Fatal error in PHP 8 لە PHP 8دا |
{$prices['Tires']} | Correct (recommended)دروستە (پێشنیارکراو) | Not used outside stringsلە دەرەوەی بەکارنایەت |
Useful built-in array functionsچەند کرداری ئامادەی بەسوود بۆ ڕیزەکەکان
PHP has many built-in functions for arrays. You have already met count(), print_r() and var_dump(). Four more are useful from the first day:
PHP چەندین بۆ هەیە. پێشتر count()، print_r() و var_dump()ت ناسیوە. چواری تر لە یەکەم ڕۆژەوە بەسوودن:
| Function | Returnsدەگەڕێنێتەوە | Exampleنموونە |
|---|---|---|
count($a) | The number of elementsژمارەی | count([72, 95, 88]) → 3 |
max($a) | The highest valueبەرزترین | max([72, 95, 88]) → 95 |
min($a) | The lowest valueنزمترین | min([72, 95, 88]) → 72 |
array_sum($a) | The sum of all valuesکۆی هەموو | array_sum([72, 95, 88]) → 255 |
end($a) | The last element (or false if the array is empty)دوایین (یان false ئەگەر بەتاڵ بێت) | end($fruits) → "orange" |
count()، max()، min()، array_sum() و end()PHPRuns on the serverلەسەر ڕاژەکاری وێب کار دەکات<?php
$marks = [72, 95, 88, 64];
echo "Count: " . count($marks) . "<br>";
echo "Highest: " . max($marks) . "<br>";
echo "Lowest: " . min($marks) . "<br>";
echo "Total: " . array_sum($marks) . "<br>";
$fruits = array("apple", "banana", "orange");
$last_fruit = end($fruits);
echo $last_fruit; //Output: orangeCount: 4 Highest: 95 Lowest: 64 Total: 319 orange
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
Count: 4<br>Highest: 95<br>Lowest: 64<br>Total: 319<br>orangeExplain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
max()returns the highest value. The name says it all.max()بەرزترین دەگەڕێنێتەوە. ناوەکەی خۆی ڕوونی دەکاتەوە.- Lineدێڕی 6
array_sum()adds all the values: 72 + 95 + 88 + 64 = 319.array_sum()هەموو کۆ دەکاتەوە: 72 + 95 + 88 + 64 = 319.- Lineدێڕی 8-10
end()returns the last element of the array.end()دوایین دەگەڕێنێتەوە.
max() works on associative arrays too. It looks at the values, not the keys:
max() لەسەر کار دەکات. سەیری دەکات، نەک :
max() لەسەر ڕیزەکێکی پەیوەندیدارPHPRuns on the serverلەسەر ڕاژەکاری وێب کار دەکات<?php
$ages = ['Aram' => 22, 'Dilan' => 18, 'Hana' => 20];
echo max($ages); // 22: max() looks at the values, not the keys22
Useful built-in array functionsچەند کرداری ئامادەی بەسوود بۆ ڕیزەکەکان
More about end()زیاتر دەربارەی end()
The Kurdish course notes describe end() like this: it gets the last element of an array, and if the array is empty it returns false. Two more facts are useful:
تێبینییە کوردییەکانی کۆرسەکە end() بەم شێوەیە وەسف دەکەن: دوایین وەردەگرێت و ئەگەر بەتاڵ بێت false دەگەڕێنێتەوە. دوو ڕاستیی تر بەسوودن:
end()also moves the array's internal "current position" marker to the last element. This matters only if you later use functions such ascurrent()ornext().end()needs a variable.end(["a", "b"])stops with Fatal error: end(): Argument #1 ($array) could not be passed by reference. Store the array in a variable first.
end()هەروەها نیشانەی «شوێنی ئێستا»ی ناوخۆیی دەباتە سەر دوایین . ئەمە تەنها گرنگە ئەگەر دواتر وەکcurrent()یانnext()بەکاربهێنیت.end()ی پێویستە.end(["a", "b"])بە Fatal error: end(): Argument #1 ($array) could not be passed by reference دەوەستێت. سەرەتا لە هەڵبگرە.
end() لەسەر ڕیزەکێکی بەتاڵPHPRuns on the serverلەسەر ڕاژەکاری وێب کار دەکات<?php
$nothing = [];
var_dump(end($nothing)); // an empty array has no last elementbool(false)
Worked homework: associative arraysئەرکی ماڵەوەی چارەسەرکراو: ڕیزەکە پەیوەندیدارەکان
Two students handed in answers to the same array homework. One file answers five questions; the question texts were not saved, so the tasks below are rebuilt from the answers. Personal details are replaced with neutral ones. Questions 4 and 5 are about sorting and are worked in the sorting lecture.
دوو خوێندکار چارەسەری هەمان ئەرکی ماڵەوەی ناردووە. یەکێک لە فایلەکان پێنج پرسیار چارەسەر دەکات؛ دەقی پرسیارەکان پاشەکەوت نەکراون، بۆیە ئەرکەکانی خوارەوە لە چارەسەرەکانەوە دووبارە دروست کراونەتەوە. زانیارییە کەسییەکان بە زانیاریی بێلایەن گۆڕدراون. پرسیاری 4 و 5 دەربارەی و لە وانەی ڕیزکردندا چارەسەر کراون.
Create an associative array of your personal information with the keys ID, Name, Age, Department and City. Print every key and value with foreach.
بۆ زانیارییە کەسییەکانت دروست بکە بە ID، Name، Age، Department و City. هەموو و بە foreach چاپ بکە.
Show answerوەڵامەکە پیشان بدە
<?php
echo "Question 1's Answer: <br />";
$personalInformation = array(
'ID' => "1",
'Name' => "Aram Karim",
'Age' => 22,
'Department' => "IT",
'City' => "Slemani"
);
echo "An associative array: ";
foreach ($personalInformation as $key => $value) {
echo $key . ": " . $value . " — ";
}Question 1's Answer: An associative array: ID: 1 — Name: Aram Karim — Age: 22 — Department: IT — City: Slemani —
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
Question 1's Answer: <br />An associative array: ID: 1 — Name: Aram Karim — Age: 22 — Department: IT — City: Slemani —Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4-8
Five key–value pairs. The ID is stored as the string
"1", the age as the integer22.پێنج . ID وەک
"1"هەڵگیراوە، تەمەن وەک22.- Lineدێڕی 11
$keygets "ID", "Name", …;$valuegets "1", "Aram Karim", …$key"ID"، "Name"، … وەردەگرێت؛$value"1"، "Aram Karim"، …- Lineدێڕی 12
Prints
key: value —for each element.بۆ هەر
key: value —چاپ دەکات.
The student's explanation (written in Kurdish with Latin letters): the array is associative because every element is made of two related parts, the key and the value; ID, Name, Age, Department and City are the keys, and through a key you reach its value. foreach means "for each of": for each item, the loop gives the key and the value to two new variables. With one variable you would get only the values.
ڕوونکردنەوەی خوێندکارەکە (بە کوردی و بە پیتی لاتینی نووسراوە): پەیوەندیدارە چونکە هەر لە دوو بەشی پەیوەندیدار پێک دێت، و ؛ ID، Name، Age، Department و City و لە ڕێگەی دەگەیتە . foreach واتە «بۆ هەریەک لە»: بۆ هەر ، و دەداتە دوو نوێ. بە یەک تەنها وەردەگریت.
Create an associative array of students and their ages. Write a function sumValuesInArray($array) that returns the sum of all the values. Print the array and the sum.
بۆ خوێندکاران و تەمەنەکانیان دروست بکە. بنووسە بە ناوی sumValuesInArray($array) کە کۆی هەموو بگەڕێنێتەوە. و کۆکەی چاپ بکە.
Show answerوەڵامەکە پیشان بدە
<?php
$students = array(
'Aram' => 22,
'Dilan' => 18
);
function sumValuesInArray($array) {
$summedValues = 0;
foreach ($array as $age) {
$summedValues += $age;
}
return $summedValues;
}
echo "The associative array: ";
foreach ($students as $key => $value) {
echo $key . ": " . $value . " — ";
}
echo "<br />Sum of all the values in the array: " . sumValuesInArray($students);
echo "<br />The same with array_sum(): " . array_sum($students);The associative array: Aram: 22 — Dilan: 18 — Sum of all the values in the array: 40 The same with array_sum(): 40
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
The associative array: Aram: 22 — Dilan: 18 — <br />Sum of all the values in the array: 40<br />The same with array_sum(): 40Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 7
Start the total at 0, outside the loop.
کۆکە لە 0ەوە دەست پێبکە، لە دەرەوەی .
- Lineدێڕی 8-10
On every iteration
+=adds the current age to$summedValues.لە هەموو
+=تەمەنی ئێستا دەخاتە سەر$summedValues.- Lineدێڕی 11
returnsends the total back to the place where the function was called: theechoon line 18.returnکۆکە دەگەڕێنێتەوە بۆ ئەو شوێنەی لێی بانگ کراوە:echoی دێڕی 18.- Lineدێڕی 19
The built-in
array_sum()does the same job in one call.array_sum()هەمان کار بە یەک بانگکردن دەکات.
The student's explanation: the values must be numbers because the job is summing, and arithmetic works on integers and floats. The function receives the array as its argument and gives it to foreach; on each iteration the value is added with += (an assignment operator) into $summedValues, which was defined outside the loop; finally return sends the total back to where the function was called. The student also wrote that foreach is used only for arrays, so the argument must be an array. For this course that is the right rule; strictly speaking, foreach can also go through the properties of an object, a topic for later.
ڕوونکردنەوەی خوێندکارەکە: دەبێت ژمارە بن چونکە کارەکە کۆکردنەوەیە و ژمێریاری (کۆکردنەوە، لێدەرکردن و هتد) لەسەر و کار دەکات. وەک وەردەگرێت و دەیداتە foreach؛ لە هەر بە += () دەخرێتە ناو $summedValues، کە لە دەرەوەی پێناسە کراوە؛ لە کۆتاییدا return کۆکە دەگەڕێنێتەوە بۆ ئەو شوێنەی لێی بانگ کراوە. خوێندکارەکە هەروەها نووسیویەتی کە foreach تەنها بۆ بەکاردێت، بۆیە دەبێت بێت. بۆ ئەم کۆرسە ئەمە یاسایەکی دروستە؛ بە وردی، foreach دەتوانێت بە بڕوات، کە بابەتێکی دواترە.
Using the same array, find and print the highest value with a function.
بە هەمان ، بە بەرزترین بدۆزەرەوە و چاپی بکە.
Show answerوەڵامەکە پیشان بدە
<?php
$students = array(
'Aram' => 22,
'Dilan' => 18
);
function highestValue($array2) {
return max($array2);
}
echo "Highest value in the array: " . highestValue($students);Highest value in the array: 22
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 7-9
The function only wraps the built-in
max().echo max($students);alone would be enough.تەنها
max()ـی ئامادە دەپێچێتەوە.echo max($students);بە تەنها بەس دەبوو.
The student's explanation: the built-in function max gives the biggest number among the values ("the function's name says it all"), and the value is returned to where the function was called, as in question 2.
ڕوونکردنەوەی خوێندکارەکە: max گەورەترین ژمارە لەنێوان دەدات («ناوی خۆی ڕوونی دەکاتەوە») و دەگەڕێتەوە بۆ ئەو شوێنەی لێی بانگ کراوە، وەک پرسیاری 2.
Common mistakesهەڵە باوەکان
- Curly quotes copied from slides or Word (
‘Tires’,“BMW”): parse error. Type straight quotes in a code editor. - Forgetting
$inforeach ($cars as value): parse error. Every variable starts with$. echo $array;prints onlyArrayand a warning. Useprint_r(),var_dump()or a loop.- Starting to count at 1. The first element is
[0]; the last is[count($a) - 1]. <=in a for loop:for ($x = 0; $x <= count($a); $x++)asks for one index too many (Undefined array key). Use<.- No separator between echoed values (
BMWNISSANJAGUAR…). Add"<br>"or", ". - Unquoted key outside a string (
$prices[Tires]): fatal error in PHP 8. Write$prices['Tires']. - Quoted key in simple interpolation (
"$prices['Tires']"): parse error. Use"{$prices['Tires']}". - Using a
forloop with an associative array. Its keys are not 0, 1, 2; useforeach. - Reusing an old array by accident. Assigning
$a['One'] = …adds to any$athat already exists. Start with$a = [];. - Writing the same key twice in one array: the second value silently replaces the first.
- Float keys such as
3.14: the key becomes3(deprecated). Use strings ("3.14") if you need decimals as keys.
- گوتەی خوار کە لە سلاید یان Wordـەوە کۆپی کراون (
‘Tires’،“BMW”): . گوتەی ڕاست لە بنووسە. - لەبیرچوونی
$لەforeach ($cars as value)دا: . هەموو بە$دەست پێدەکات. echo $array;تەنهاArrayو چاپ دەکات.print_r()،var_dump()یان بەکاربهێنە.- دەستپێکردنی ژماردن لە 1ـەوە. یەکەم
[0]ـە؛ دوایینیان[count($a) - 1]ـە. <=لە :for ($x = 0; $x <= count($a); $x++)داوای زیاتر لە پێویست دەکات (Undefined array key).<بەکاربهێنە.- بێ جیاکەرەوە لەنێوان چاپکراودا (
BMWNISSANJAGUAR…)."<br>"یان", "زیاد بکە. - بێ گوتە لە دەرەوەی (
$prices[Tires]): لە PHP 8دا. بنووسە$prices['Tires']. - گوتەدار لە سادەدا (
"$prices['Tires']"): ."{$prices['Tires']}"بەکاربهێنە. - بەکارهێنانی لەگەڵ . 0، 1، 2 نین؛
foreachبەکاربهێنە. - بەکارهێنانەوەی کۆن بەبێ ئاگاداری. دانانی
$a['One'] = …دەچێتە سەر هەر$aـێک کە پێشتر هەبێت. بە$a = [];دەست پێبکە. - نووسینی هەمان دوو جار لە یەک : دووەم بێدەنگ یەکەم دەگۆڕێت.
- وەک
3.14: دەبێتە3(). ئەگەر ژمارەی دەییت وەک پێویستە بەکاربهێنە ("3.14").
Exercisesڕاهێنانەکان
Lab 4, Example 6 (one-dimensional array). Create an array of the numbers 1 to 5 with array() (first method) and print each value as "Value is …" on its own line with foreach. Then create a second array by assigning "one" to "five" to the indexes 0 to 4 (second method) and print it the same way.
تاقیگەی 4، نموونەی 6 ( یەک ڕەهەندی). ژمارەکانی 1 تا 5 بە array() دروست بکە (ڕێگای یەکەم) و هەر وەک «Value is …» لە دێڕێکی جیادا بە foreach چاپ بکە. پاشان دووەم دروست بکە بە دانانی "one" تا "five" لە 0 تا 4دا (ڕێگای دووەم) و بە هەمان شێوە چاپی بکە.
Show answerوەڵامەکە پیشان بدە
<?php
/* First method to create array. */
$numbers = array(1, 2, 3, 4, 5);
foreach ($numbers as $value) {
echo "Value is $value <br />";
}
/* Second method to create array. */
$words[0] = "one";
$words[1] = "two";
$words[2] = "three";
$words[3] = "four";
$words[4] = "five";
foreach ($words as $value) {
echo "Value is $value <br />";
}Value is 1 Value is 2 Value is 3 Value is 4 Value is 5 Value is one Value is two Value is three Value is four Value is five
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
Value is 1 <br />Value is 2 <br />Value is 3 <br />Value is 4 <br />Value is 5 <br />Value is one <br />Value is two <br />Value is three <br />Value is four <br />Value is five <br />Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 10-14
The lab reused the name
$numbersfor both arrays. A different name,$words, makes it clear that this is a new array.تاقیگەکە ناوی
$numbersی بۆ هەردوو بەکارهێنابوو. ناوێکی جیاواز،$words، ڕوونی دەکاتەوە کە ئەمە نوێیە.
An array: store five names, then print them one under the other.
: پێنج ناو هەڵبگرە، پاشان یەک لەژێر ئەوی تردا چاپیان بکە.
Hintئاماژە
Use foreach and print "<br>" after each name.
foreach بەکاربهێنە و دوای هەر ناوێک "<br>" چاپ بکە.
Show answerوەڵامەکە پیشان بدە
<?php
$names = ["Aram", "Shilan", "Karwan", "Dilan", "Rezan"];
foreach ($names as $name) {
echo $name . "<br>";
}Aram Shilan Karwan Dilan Rezan
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
Aram<br>Shilan<br>Karwan<br>Dilan<br>Rezan<br>Exam question: "What are the types of arrays? Explain them and give each an example."
پرسیاری تاقیکردنەوە: «جۆرەکانی چین؟ ڕوونیان بکەرەوە و بۆ هەریەکەیان نموونەیەک بهێنەرەوە.»
Show answerوەڵامەکە پیشان بدە
- Indexed array: values have numeric indexes that start at 0, e.g.
$colors = ["red", "green", "blue"];and$colors[0]is "red". - Associative array: each value has a named key, e.g.
$capitals = ["Kurdistan Region" => "Erbil"];. - Multidimensional array: an array that contains arrays, e.g. a timetable
[["Sunday", "PHP"], ["Monday", "Networks"]], read with two indexes:$timetable[1][0].
- : ژمارەییان هەیە کە لە 0ەوە دەست پێدەکەن، بۆ نموونە
$colors = ["red", "green", "blue"];و$colors[0]دەکاتە "red". - : هەر ناوداری هەیە، بۆ نموونە
$capitals = ["Kurdistan Region" => "Erbil"];. - : کە چەند تری تێدایە، بۆ نموونە خشتەی وانەکان
[["Sunday", "PHP"], ["Monday", "Networks"]]، کە بە دوو دەخوێنرێتەوە:$timetable[1][0].
<?php
// Indexed array: keys 0, 1, 2 are given automatically
$colors = ["red", "green", "blue"];
echo $colors[0] . "<br>";
// Associative array: we choose the keys
$capitals = ["Kurdistan Region" => "Erbil", "Iraq" => "Baghdad"];
echo $capitals["Kurdistan Region"] . "<br>";
// Multidimensional array: an array of arrays
$timetable = [
["Sunday", "PHP"],
["Monday", "Networks"],
];
echo $timetable[1][0] . ": " . $timetable[1][1];red Erbil Monday: Networks
HTML sent to the browserئەو HTMLـەی دەنێردرێت بۆ تۆڕگەڕ
red<br>Erbil<br>Monday: NetworksSummary and reviewکورتە و پێداچوونەوە
- An array stores many values under one name. PHP has indexed, associative and multidimensional arrays.
- Create arrays with
array(…)or[…];[]alone is an empty array. Assigning to$a[0],$a['key']or$a[]also creates or extends an array. - Automatic indexes start at 0; the last index is
count($a) - 1. The next automatic key is the largest integer key + 1. - Keys are integers or strings only.
"42"becomes42, floats are cut,truebecomes1. A repeated key replaces the old value. echocannot show an array (it printsArraywith a warning). Useprint_r()(inside<pre>) orvar_dump().- Loop with
foreach ($a as $value)orforeach ($a as $key => $value); or withforandcount()using<. - Quote string keys in code:
$a['key']. In strings use"{$a['key']}"(or"$a[key]"without quotes). - Useful functions:
count(),max(),min(),array_sum(),end(),implode().
- چەندین لەژێر یەک ناودا هەڵدەگرێت. PHP ، و هەیە.
- بە
array(…)یان[…]دروست بکە؛[]بە تەنها بەتاڵە. دانانی بۆ$a[0]،$a['key']یان$a[]یش دروست دەکات یان گەورەی دەکات. - خۆکار لە 0ـەوە دەست پێدەکەن؛ دوایین
count($a) - 1ـە. خۆکاری داهاتوو دەکاتە گەورەترین + 1. - تەنها یان .
"42"دەبێتە42، دەبڕدرێن،trueدەبێتە1. دووبارە کۆن دەگۆڕێت. echoناتوانێت پیشان بدات (Arrayلەگەڵ چاپ دەکات).print_r()(لەناو<pre>دا) یانvar_dump()بەکاربهێنە.- بە
foreach ($a as $value)یانforeach ($a as $key => $value)بخولێنەوە؛ یان بەforوcount()بە بەکارهێنانی<. - لە کۆددا لەناو گوتەدا بنووسە:
$a['key']. لەناو"{$a['key']}"بەکاربهێنە (یان"$a[key]"بەبێ گوتە). - بەسوود:
count()،max()،min()،array_sum()،end()،implode().
What is the difference between an index and a key?جیاوازیی نێوان ئیندێکس و کلیل چییە؟
An index is a numeric key (0, 1, 2 …) used by indexed arrays. "Key" is the general word: in associative arrays keys are usually strings. Every element has exactly one key.
ژمارەییە (0، 1، 2 …) کە بەکاری دەهێنن. «» وشە گشتییەکەیە: لە زۆرجار . هەموو ڕێک یەک هەیە.
Why does count() give 3 for an array whose last index is 2?بۆچی count() بۆ ڕیزەکێک کە دوایین ئیندێکسی 2ـە، 3 دەدات؟
count() counts elements starting from 1; indexes start from 0. So the last index is always count - 1.
count() لە 1ەوە دەژمێرێت؛ لە 0ەوە دەست پێدەکەن. بۆیە دوایین هەمیشە count - 1ـە.
How do you print both the keys and the values of an associative array?چۆن هەم کلیلەکان و هەم نرخەکانی ڕیزەکێکی پەیوەندیدار چاپ دەکەیت؟
With foreach ($array as $key => $value) { echo "$key: $value<br>"; }.
بە foreach ($array as $key => $value) { echo "$key: $value<br>"; }.
What is wrong with echo $prices[Oil]; in PHP 8?echo $prices[Oil]; لە PHP 8دا چ هەڵەیەکی هەیە؟
Without quotes, Oil is read as a constant name. It does not exist, so PHP stops with Error: Undefined constant "Oil". Write $prices['Oil'].
بەبێ گوتە، Oil وەک ناوی دەخوێنرێتەوە. بوونی نییە، بۆیە PHP بە Error: Undefined constant "Oil" دەوەستێت. بنووسە $prices['Oil'].
Which keys does array("a" => 1, 2, 3) have?array("a" => 1, 2, 3) چ کلیلێکی هەیە؟
"a", 0 and 1. The values without keys are numbered from 0 because there was no integer key before them.
"a"، 0 و 1. بێ لە 0ەوە ژمارە دەکرێن چونکە پێش ئەوان هیچ نەبوو.
What does end() return for an empty array?end() بۆ ڕیزەکێکی بەتاڵ چی دەگەڕێنێتەوە؟
false.
false.
Videoڤیدیۆ
Watch a videoسەیری ڤیدیۆیەک بکە
A video that viewers liked a lot and praised in their comments, chosen for this lesson.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.
How to create indexed and associative arrays, read, change and delete elements, and print a whole array to see its structure.
چۆن و دروست بکەیت، بخوێنیتەوە، بگۆڕیت و بسڕیتەوە و هەموو پیشان بدەیت تا پێکهاتەکەی ببینیت.
Watch 0:00–11:57: indexed and associative arrays, printing arrays
لە 0:00 تا 11:57 سەیر بکە: و و پیشاندانی .
Lesson complete!وانەکە تەواو بوو!
Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.
Key termsزاراوە سەرەکییەکان
Multidimensional Arraysڕیزەکە فرەڕەهەندەکان
Related lecturesوانە پەیوەندیدارەکان
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.