Show Menu
Cheatography

PHP Arrays Cheat Sheet by

simple cheatsheet for php array functions, declaration.

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 
$p1 = array("China", "Russia", "Austria", "Turkey");
$p2 = array
(
'china' => "Beijing",
'Russia' => "Moscow" ,
'Austria' => "Vienna",
'Turkey' => "Ankara"
);

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 = explode(' ', "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. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.