Arrays in PHP - ProgrammerTech
Language:

Search

Arrays in PHP

  • Share this:
Arrays in PHP

Arrays PHP

Arrays are a means of storing data of one type temporarily. The purpose of using arrays is to store data, and an array list can contain a set of elements of one or more data types. The data in the array is enclosed in square brackets [].

It is also known as a technique or tool for storing data of one type temporarily, and it is divided into several cells, and each cell has an index address, so it is easy for us to process, arrange, sort, and search data using arrays.

More clarification (Imagine a list of words separated by a comma called the comma separated list). It will be in the form

kaissar , data , spider , Ali , Lana , Ahmed

That's the idea and remember when I talked to you above, it's a set of elements with each element having its own name and number. The role of the arrays is to give each of those names a number and an identification so that I can use them in the script.

Before you start do you know the function of matrices?

Imagine with me that you build a program and that program contains a large group of employees in a company.

Are you going to put every name inside a variable?

The number of employees may be more than 1000, what are you doing here?

Answer: You have to use matrices.

Arrays in php are divided into three sections:

  1. indexed arrays.
  2. Associative Arrays.
  3. Multidimensional Arrays.

 

indexed Array PHP

An indexed array is an array that contains a set of numeric index keys, and each of these keys contains a stored value.

Example

Write a program that defines your websit's programming languages ​​into an array.

<?php
    $lng = array("html" , "html5" , "css" , "css3" , "js" , "php"); 
    print_r($lng);
?>

I used the lng variable and inside the variable there is an Array, that is, it is the function responsible for printing the arrays. of type indexed array, then you enter the index we want in parentheses. The general form for writing an indexed array is as.

$name = array(Element , Element , Element);

The second function print_r is the function responsible for printing the data inside the array. Not the same as echo it prints all the contents of the array in terms of the name and id of each index. It starts from zero to infinity and the output will be in the server form.

Array ( [0] => html [1] => html5 [2] => css [3] => css3 [4] => js [5] => php )

The <pre> tag can be used for a line down for every index.

<?php
    $lng = array("html" , "html5" , "css" , "css3" , "js" , "php"); 
    echo "<pre>";
    print_r($lng);
    echo "<pre>";
?>

server output

<pre>Array
(
    [0] => html
    [1] => html5
    [2] => css
    [3] => css3
    [4] => js
    [5] => php
)
pre

Now some of you will say: You said that arrays are a set of elements where each element has a definition and a number. How do we call one of the internal indexes through the number, of course, the index that has the name html has a number. If you want to print an element by number, you should use the echo function instead of print_r, which is the responsible function. Only about printing the entire contents of the array and not an element inside it and if you want to print an element by number you have to use .

echo $lng[0]

You get the element number and put it inside the parentheses after the variable. But now this matrix is ​​not smart, and we want to develop further, it could be a matrix within an array.

<?php
    $lng = array("html" , "html5" , "css" , array("font", "size") , "js" , "php"); 
    echo "<pre>";
    print_r($lng);
    echo "<pre>";
?>

Notice how an array is written into an array and this type of array is used to state something inside an element. For example, the css3 element has font and size, which are the font and size, and it will be in the server format.

<pre>Array
(
    [0] => html
    [1] => html5
    [2] => css
    [3] => Array
        (
            [0] => font
            [1] => size
        )
    [4] => js
    [5] => php
)
<pre>

Notice how the browser's output was telling you that the third type of this index is an array and all its elements such as size , font and also have numbers for each element.

How do we print a font element?

<?php
    $lng = array("html" , "html5" , "css" , array("font", "size"), "js" , "php"); 
    echo $lng[3][0];
?>

Just write the numbers of the elements in order inside the parentheses. We know that the inner array is one of the elements and has a number which is 3 and has an array. It also includes internal elements such as font and its number 0, and it is printed via echo $lng[3][0]. Now the array is not smart. Let's take it further and use for loops in the array.

<?php
    $lng = array("html", "html5", "css",array("font" , "size") , "js" , "php" );
    echo "<ul>";
    for ($i= 0; $i< count($lng) ;$i++)
    {
        echo "<ul>";
        echo "<li>" . $i . "</li>";
    }
?>

Note that we created a loop so that the number of items in the array was printed and we used the count function with it. Here we say the variable i=0, then we say the variable i<count for the variable lng, then we say i++ here is increasing the value. That is, every time until you reach the number of elements in the array and the result will be the numbers of the elements only. If you want to print an element, you need to type the element number echo $lng[2] and if you want to print the names of the elements. Inside the loop, you just have to write the name of the variable that contains the array data in the print function of the form.

<?php
    $lng = array("html" , "html5" , "css" , "css3" , "js" , "php"); 
    echo "<ul>";
    for ($i= 0; $i< count($lng) ;$i++)
    {
        echo "</ul>";
        echo "<li>" . $lng[$i]. "</li>";
    }
?>

The output will be inside an unordered ul list as follows.

  • html
  • css
  • php
  • javascript

 

Associative Array PHP

Associative Array This type of array takes a key and a value, ie it is key : value. The first type is indexed array. Only the value is specified and based on that the key is selected., But in that type a value is given to the key or a name, but it must be of type int numbers or strings.

Example

Suppose you are a student studying at Cairo University in the field of programming and take a group of languages, and you want to determine your level in each language.

<?php
    $langs = array
    (
        "html5"                 => "50%",
        "css3"                    => "60%",
        "javascript"           => "30%",
        "php"                     => "70%",
        "python"                => "80%",
     );
?>

We have created an array of some of the languages ​​offered by this site with your level percentage for each language. At the beginning we talked that this type of array has a key and a value and that key is the names of the languages ​​you learn in this site. As for the value, this is the percentage of your education and your level for each language.

<?php
    $langs = array
    (
        "html5"                 => "50%",
        "css3"                    => "60%",
        "javascript"           => "30%",
        "php"                     => "70%",
        "python"                => "80%",
     );
    foreach ($langs as  $kaissar)
    {
        echo   $kaissar ;
    };
?>

We created a foreach to make a rotation on the values ​​inside the Array. Then we create a variable named kaissar that will search its contents. The variable langs will then print the spin and the output will be on the server.

50%60%30%70%80%

But now the image is not good let's print the output into an unordered list and the code will be. Or code like that.

<?php
    $langs = array
    (
        "html5"                 => "50%",
        "css3"                    => "60%",
        "javascript"           => "30%",
        "php"                     => "70%",
        "python"                => "80%",
     );
     echo "<ul>";
    foreach ($langs as  $kaissar)
    {
        echo "<li>" . $kaissar ."</li>";
    };
    echo "<ul>";
?>

When running, the output will be in the server as

  • 50%
  • 60%
  • 30%
  • 70%
  • 80%

But now foreach printed the value only and I didn't know what elements contain that value. Let's develop the code to print the element and the value it carries.

<?php
    $langs = array
    (
        "html5"                 => "50%",
        "css3"                    => "60%",
        "javascript"           => "30%",
        "php"                     => "70%",
        "python"                => "80%",
     );
     echo "<ul>";
    foreach ($langs as $programmer =>  $kaissar)
    {
        echo "<li>" . $kaissar ." => ".$programmer . "</li>";
    };
    echo "<ul>";
?>

We used foreach to do a spin on the value and key, that's what foreach does. About the other rotation because it contains a value and a key. We created a variable called programmer to search within the element in the array and also created another variable. In the name of kaissar to search inside the value and the result will be on the server in the form.

  • 50%  =>html5
  • 60%  =>css
  • 30%  =>javascript
  • 70%  =>php
  • 80%  =>python

Now the question here is how do I add a new item? You can add the new element like this

<?php
    $langs = array
    (
        "html5"                 => "50%",
        "css3"                    => "60%",
        "javascript"           => "30%",
        "php"                     => "70%",
        "python"                => "80%",
     );
     $langs{"mysql"}="88%";
     echo "<ul>";
    foreach ($langs as $programmer =>  $kaissar)
    {
        echo "<li>" . $kaissar ." => ".$programmer . "</li>";
    };
    echo "<ul>";
?>

We added a new element called mysql + value 88%, but notice how we assign a value or an element inside the lange variable through parentheses. We tell the private interpreter in php to create or assign a value to the contents or values ​​of the lange variable of type array. And here the interpreter understands that this is a type of data from the array, but note that I have inside. The parentheses label the element that is mysql and the output on the server will be in the form.

  • 50%  =>html5
  • 60%  =>css
  • 30%  =>javascript
  • 70%  =>php
  • 80%  =>python
  • 88% =>mysql

But what if I don't put the name of the element inside the parentheses. Here the interpreter will understand that this type of data is an array but. of type indexed array and the element name will be added in order from 0 to & let's do that now.

<?php
    $langs = array
    (
        "html5"                 => "50%",
        "css3"                    => "60%",
        "javascript"           => "30%",
        "php"                     => "70%",
        "python"                => "80%",
    );
     $langs[]="88%";
     $langs[]="78%";
     $langs[]="84%";
     echo "<ul>";
    foreach ($langs as $programmer =>  $kaissar)
    {
        echo "<li>" . $kaissar ." => ".$programmer . "</li>";
    };
    echo "<ul>";
?>

Now the interpreter will understand that this type of data is array indexed and will name the elements by itself. The output will be on the server.

  • 50%  =>html5
  • 60%  =>css
  • 30%  =>javascript
  • 70%  =>php
  • 80%  =>python
  • 88% =>0
  • 78% =>1
  • 84% =>2

Now we come to the other types of data that can be added inside the array. It is null which means null and True means 1 false and 0 means and the example would look like this.

<?php
    $langs = array
    (
         null     =>   "53",
         true     =>    "54",
         false    =>   "55",
        "html5"                 => "50%",
        "css3"                    => "60%",
        "javascript"           => "30%",
        "php"                     => "70%",
        "python"                => "80%",
    );
     echo "<ul>";
    foreach ($langs as $programmer =>  $kaissar)
    {
        echo "<li>" . $kaissar ." => ".$programmer . "</li>";
    };
    echo "<ul>";
?>

 

Multidiminsional Array PHP

An array ( Multidiminsional Array ) is an array in which we can create a set of arrays such as Indexed Array and Associative Array.

In the first two arrays, where each of them was specialized in something, it was possible to create an array with an indexed Array inside it, and the same was true with the second type, which is the Assocarive Array, and the opposite could not happen, which is the one inside the indexed Array inside the Assocative Array. But it can happen with Array Multidimensional Let's take some examples of this type and see how it works.

The general formula for writing a multidimensional array

[3] Array Multidimensional
    Syntax :
    array(
        array( Element , Element , Element),
        array( Element , Element , Element ),
        array( Element , Element , Element ),
        );

 

Example
<?php
$Array = array(
    array("Python" , "Java" , "C#"),
    array("html", "html5", "css3"),
    array("Java network", "python network", "c#network"),
    array("html index", "html5 index", "css3 style index.1.2"),
    array("python information security", "java information security", "c# information security"),
    );
    echo "<pre>";
    print_r($Array);
    echo "</pre>";
?>

We have created an array inside a variable called Array with a set of sub-arrays inside. Suppose the matrix will be the courses that our site will offer over the next five days. The sub-array number 0 holds the languages ​​that we will introduce on the first day and they are #Python And Java And C.

On the second day we will introduce the languages ​​Html And Html5 And Css3 and then the site will use those languages ​​mentioned in the array. Number 0 in networks and python will be used in networks as well as java and C#. I think you understand the method, notice when all the contents of the main matrix are printed. And as we know it is called Array and using print_r the array can be printed.

A main array holds a set of sub-arrays. It is also possible to print a specific thing from within the sub-arrays because each sub-array has a number. Suppose we want to print the html index cycle which is inside the sub-array number 3 and the html index element number 0 as you can see in the image.

You can print through the code [echo $Array[3][0], note that you talk to the code exactly as if you were talking to one of your friends. I told him to print from inside the main array the sub-array number 3 and from inside the sub-array print the element number 0 which is the html index. But so far the example hasn't been complicated. It's just an array within an array. Let's complicate the example further through another example.

Example

Let's say for example the cycles mentioned inside sub-array number 3 which have html index, html5 index and css3 style index.1.2. And we want to mention the work team that works on those courses within an array with a set of sub-arrays.

I mean, it will be a sub-array inside another sub-array, and that array will have powers. specific about the subarrays it contains. And the work team that will provide these courses will be Ali, Ahmed, date, kaissar, lana and spider.

<?php
$Array = array(
    array("Python" , "Java" , "C#"),
    array("html", "html5", "css3"),
    array("Java network", "python network", "c#network"),
    array("html index", "html5 index", "css3 style index.1.2"),
    array(
             array("Ahmed", "Ali", "Data"),
             array("ksaissar", "lana", "spider"),
          ),
    array("python information security", "java information security", "c# information security"),
    );
    echo "<pre>";
    print_r($Array);
    echo "</pre>";
?>

Watch how the operation was performed and we now know that matrix No. 4 has sub-arrays as well. Here it has a sub-array number 0 and it has elements, and also there is another matrix numbered 1 and it has elements. And now we want to print the spider inside the sub-array. No. 1 and Subarray No. 4 Enter a main array named Array. And the print code will be [echo $Array[4][1][2.

A subarray can also be created within a subarray anywhere within the main array. But so far we are dealing with an indexed Array and we are taking an example of how to create an Associative Array.

Example
<?php
$Array = array(
    'Dey 1' =>array("Python" , "Java" , "C#"),
    'Dey 2' =>array("html", "html5", "css3"),
    'Dey 3' =>array("Java network", "python network", "c#network"),
    'Dey 4' =>array("html index", "html5 index", "css3 style index.1.2"),
    'Dey 5' =>array("python information security", "java information security", "c# information security"),
    );
    echo "<pre>";
    print_r($Array);
    echo "</pre>";
?>

In the code nothing changed except the type of the array and we converted the array from type Indexed Array to Associative Array. And it will be the shape of the matrix after printing.

And as you can print any element from inside any array, for example we want to print html5 element from inside the Dey 2 array. The form of the operation while printing the element will be [echo $Array ['Dey 2'][0. Let's create sub-arrays inside each array and those arrays will be the names of the people presenting each of them.

<?php
$Array = array(
    'Dey 1' =>array("Python" , "Java" , "C#", array(
                       'python' => 'kissar',
                       'java' => 'data',
                       'python' => 'saja'
                       )),
    'Dey 2' =>array("html", "html5", "css3",array(
                      'html' => 'kissar',
                      'html5' => 'Ali',
                      'css3' => 'Spider'
                      )),
    'Dey 3' =>array("Java network", "python network", "c# network",array(
                     'Java network' => 'Yosef',
                     'python network' => 'ibrahim',
                     'c# network' => 'muhammad'
                     )),
    'Dey 4' =>array("html index", "html5 index", "css3 style index.1.2"(
                     'html index' => 'mhammad',
                     'html5 index' => 'salah',
                     'css3 style index.1.2' => 'kamal'
                     )),
    'Dey 5' =>array("python information security", "java information security", "c# information security",array(
                   'python information security' => 'parrot',
                   'java information security' => 'wzer',
                   'c# information security' => 'ahmd'
                    )),
    );
    echo "<pre>";
    print_r($Array);
    echo "</pre>";
?>

See what the code was like before and now, the people working on the cycles are added and the sub-arrays are added nicely.

Now any element can be printed from within any array. All you have to do is know the name of the element and where the element is located. For example we want to print the name of the person who is providing the c#, network course What will the printing process be like? The printing process will be in the form.

echo $Array['Dey 3'][3]['c# network']

Now everything is clear, and if you do not understand it, write your questions in the comments of this lesson.


Tags:
Muhammad Alush

Muhammad Alush

إسمي محمد تركي العلوش من سورية من ريف حلب الشرقي 1994, محب للتقنية و التعلم الذاتي, و جميع خبراتي تعلمتها ذاتياً, و اللغات البرمجية التي أتقنها هي html, css, javascript, php, c, python بالإضافة إلى حبي الكبير لمجال الشبكات.

موقعي programmer-tech.com