How to use arrays in PHP? How often?

In PHP, there are three types of arrays:

  • Numeric array - array with numeric ID key
  • Associative array - an array with specified keys, each associated with a value
  • Multidimensional array - an array containing one or more arrays

See specific examples:

 

Create array

<?php
    //Mode 1
    $cars = array("Volvo","BMW","Toyota");
    //Mode 2
    $cars[0] = "Volvo";
    $cars[1] = "BMW";
    $cars[2] = "Toyota";
    //Mode 3
    $cars = [
      "Volvo",
      "BMW",
      "Toyota",
    ]
?>

<?php
    $cars = array("Volvo","BMW","Toyota");
    echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

  

Get the length of the array - count() function

<?php
   $cars = array("Volvo","BMW","Toyota");
    echo count($cars);
?>

  

Traversal array

<?php
    $cars = array("Volvo","BMW","Toyota");
  //The first way
    $arrlength = count($cars);
    for($x = 0 ;$x < $arrlength ;$x++) {
        echo $cars[$x];
        echo "<br>";
    }
    //The second way
    foreach ($cars as $key => $value){
        echo $value;
        echo "<br/>";
    }
?>

  

Array? Chunk() function (splits an array into two element array blocks)

<?php
    $cars = array("Volvo","BMW","Toyota","Honda","Mercedes","Opel");
    print_r(array_chunk($cars,2));
?>

  

array_keys() function (returns a new array containing all the key names in the array)

<?php
    $a = array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");
    print_r(array_keys($a));
?>

  

array_push() function (insert "blue" and "yellow" at the end of the array)

<?php
    $a = array("red","green");
    array_push($a,"blue","yellow");
    print_r($a);
?>

  

Array? Pop() function (delete the last element in the array)

<?php
    $a = array("red","green","blue");
    array_pop($a);
    print_r($a);
?>

  

Array? Reverse() function (returns an array of flip order)

<?php
    $a = array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
    print_r(array_reverse($a));
?>

  

Sort() function (to sort the elements in an array alphabetically in ascending order)

<?php
    $cars = array("Volvo","BMW","Toyota");
    sort($cars);
?>

  

Tags: PHP

Posted on Sat, 25 Apr 2020 07:23:26 -0700 by scott212