PHP Arrays Cheat Sheet

A Programming › PHP cheat sheet in English by shirM

simple cheatsheet for php array functions, declaration.

4,033 views 805 downloads 7 May 2023 History

Declar­ation

explicit location
<?php
$print­er[0] = "­Las­erjet 2001";
$print­er[1] = "­LMP­172­4fa­st";
implicit location
<?php
$printer[] = "­Las­erjet 2001";
$printer[] = "­LMP­172­4fa­st";

Associ­ative Arrays

<?php
    $printer['R&B PRINTERS']= "Laserjet 2002";
    $printer['Jackson Printers'] = "J2001Laserjet";
    print_r($printer);
    
    //result
    array (
            'R&B PRINTERS' => "Laserjet 2002",
            'Jackson Printers' => "J2001Laserjet",
     )
?>
with associ­ative arrays, you can reference the items in an array by name rather than by number.

Multid­ime­nsional Arrays

<?php
 $products = array(
     'pens' => array(
         'ball' =>  "Ball Point",
         'hilite' =>  "Highlighters",
         'marker' => "Markers"),
      'misc' => array(
         'tape' =>  "Sticky Tape",
         'glue' =>  "Adhesives",
         'clips' => "Paperclips"
        )
 );

Assignment using the array Keyword

`<?php {{nl}}$p1 = array("China", "Russia", "Austria", "Turkey");  {{nl}}$p2 = array {{nl}} ({{nl}} 'china' => "Beijing", {{nl}}  'Russia' => "Moscow" ,{{nl}}  'Austria' => "Vienna", {{nl}}  'Turkey' => "Ankara" {{nl}} );

The for..each as loop

<?php
 $paper = array("Copier", "Inkjet", "Laser", "Photo");
 $j = 0;
 foreach($paper as $item)
 {
 echo "$j: $item<br>";
 ++$j;
 }
?>

Functions

Functions
is_array()
echo (is_ar­ray­($p­rod­ucts)) ? "Is an array" : "Is not an array";
count()
echo count(­$pr­odu­cts);
sort()
sort($products);
sort($products, SORT_NUMERIC);
sort($products, SORT_S­TRING);
shuffle()
shuffl­e($­cards);
explode()
<?php
$temp = explod­e(' ', "This is a sentence with seven words");
print_­r($­temp);
?>
extract()
extrac­t($­_GET);

compact()

<?php
$planet = "Gallifrey";
$system = "Gridlock";
$constellation = "Kasterborous";
$contact = compact 'planet', 'system', 'constellation');
use compact, the inverse of extract, to create
an array from variables and their values.

Comments

No comments yet.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.