php, Arrays

March 12, 2012

updated 2016-04-09

Array keys start from 0, not 1.
In an associative array a key is associated with a value.
An array in PHP is actually an ordered map. (each key is mapped to a value).
array values can be other arrays, trees and multidimensional arrays are also possible.
A value can be any PHP type.
A key may be either an integer or a string. Floats in keys are truncated to integer.
“8” will be interpreted as 8, while “08” will be interpreted as “08”
Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array.


foreach ($array as $value)
{ echo '<br>'.$value }


$result = mysql_query($query);
$recordcount = count($result) ;

 

Check if a variable exists in an array


if ( in_array($var, $array) )
{ echo $var.' is in the array' ; }
else
{ echo $var.' is not in the array' ; }

 

find where a variable is in an array


if ( in_array($var, $array) )
{ $key = array_search($var, $array); }
else
{ echo $var.' is not in the array' ; }


$ii = array_search($what, $array);
if($ii !== false and $array[$ii] == $what) :
return true;
endif;


if (($key = array_search($what, $array)) === false) :
echo "Not found";
else :
echo $key;
endif;

 

create an array:


$array = array(1, 2, 3, 4, 5, 8 => 8, 7 => 7, 19, 6 => 13);
print_r ($array);
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [8] => 8
[7] => 7 [9] => 19 [6] => 13 )
echo max($array) ;
19 (maximum value in the array)

 

convert an object to an array

$array = (array)$yourObject;

Try to Get in to the habit of always converting a QUERY result of multiple records into an indexed array (or indexed object) where you can see the record before and the record after the one you are iterating through at the moment – as well as any other record. It ALSO eliminates ATTEMPTING to reset an object-array.

Database Queries

MYSQLI Examples:

  $result = mysqli_query($socket, $query);
  # $numrows = mysqli_num_rows($result);  # *or* see "$numrows = $ii" below
  
  $ii = 0;  $row = array(); 
  while ($record = mysqli_fetch_object($result))
     { $ii += 1;   $row[$ii] = $record ; } 
  $numrows = $ii ;
  
  for($ii = 1; $ii <= $numrows ; $ii++) :
     . . . #[all your record processing]# 
     if ($row[$ii-1]->item  !==  $row[$ii+1]->item) { . . . } 
     . . . #[all your record processing]# 
  endfor;

 

 -------          -------
 $socket = mysqli_connect($dbhost, $dbuser, $dbpass) ;
 mysqli_select_db($socket, $dbname) ;
        --------- -------
 $query = 'SELECT id, name, addr, city, ... '; 
                        -------
 $result = mysqli_query($socket, $query);
                        -------

 while ($row = mysqli_fetch_object($result))

              -------
 mysqli_error($socket)
              -------

 mysqli_num_rows($result) 

                      -------
 mysqli_affected_rows($socket) ;
                      -------
                             -------
 $newkey = @mysqli_insert_id($socket); // Get the new record key that was "auto-insert"ed.
                             -------

 

  $ii = 0 ; 
  while ($record = mysqli_fetch_object($result)) :
     $ii +=1 ;
     $row[$ii] = $record ; 
  endwhile;
  $numrows = $ii ; 

  for($ii=1; $ii<=$numrows; ++$ii) : 
      echo $ii.' name: '.$row[$ii]->name.' ' ; 
      echo     ' city: '.$row[$ii]->city.' ' ; 
   endfor;

 

This example also creates a 1-based (not 0) index array.

$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
Array ( [1] => January [2] => February [3] => March )

 

sort an array
sort($array);
rsort($array);
#(reverse sort)

 

clear an array
unset($arr); // clears the entire array
unset($arr[x]); // This removes the element from the array
quotes are not necessary around the x
However, [$var] and [“$var”] will be interpreted, where [‘$var’] will not!

The unset($arr[x]) function removes the key (and its value) from an array. Be aware that the array will not be reindexed.

 

How to reindex an array

the array can be reindexed this way:
example: index starting with 1:

$ii = 1 ;
$arraynew = array();
foreach ( $arrayold as $key => $val )
{
$arraynew[$ii] = $val;
$ii++ ;
}

// delete every item, but leave the array itself intact:

foreach ($array as $i => $value)
{ unset($array[$i]); }

 

to empty an array

unset($arr); // This deletes the whole array

$Array = array(); // this creates an empty array

 

break a string into an array of values

a date example, mm/dd/yyyy

$dtarr = explode("/", $adate);
if (!checkdate($dtarr[0], $dtarr[1], $dtarr[2]) )
{ ### checkdate uses m,d,y format
$message .= 'Please enter a valid date(mm/dd/yyyy) ' ;
}

 

Convert a collection of objects to an array

to convert a 1 dimentional collection of objects to an array:

// cast the object
$array = (array)$obj;

to convert a multi-dimentional collection of objects to an array:


$array=array();
foreach($object as $member=>$data)
{ $array[$member]=$data; }

enhanced version

function objectToArray($object)
{ if(!is_object($object) && !is_array($object)) return $object;
$array=array();
foreach($object as $member=>$data)
{ $array[$member]=objectToArray($data); }
return $array;
}

$object = get_object_vars( $object );
array_map( ‘objectToArray’, $object );

 

to check if an element exists in an array

in_array(element[$x]) ;
or
in_array(element["$x"]) ;
if you use quotes at all, do not use single quotes.
Double quotes are always required to tell php to use the value of the variable
(not the literal name of the variable including the $.)

 

How to reset mysql pointer back to the first row in PHP?

while($row = mysql_fetch_array($result)){ echo $row[‘id’];}

If I use the above code two times consecutively, the row does not get printed twice.
How to reset it?

reset($arr);

 

You may have noticed that the following are functionally identical:
while (list(, $value) = each ($arr))
{ echo "Value: $value <br>\n"; }


foreach ($arr as $value)
{ echo "Value: $value <br>\n"; }

The following are also functionally identical:
reset($arr);
while (list($associativeKey, $value) = each ($arr))
{ echo "Key: $associativeKey; Value: $value <br>"; }


foreach ($arr as $key => $value)
{ echo "Key: $key; Value: $value <br>"; }

foreach ($_POST AS $key=>$value) echo ' <br> key:'.$key.' value:'.$value ;


for($i=0;$iuserkey == $dspUser[$i+1]->userkey )
{ $userstests .= ' '.$dspUser[$i]->testkey.' ' ; }
else
{ // display user record ... }


$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");

This would result in $queue having the following elements:
Array
(
[0] => apple
[1] => raspberry
[2] => orange
[3] => banana
)

See also array_shift(), array_push(), and array_pop().

// add an element to the end
array_push($queue, 'strawberry');

// remove an element from the end
array_pop($queue);

For each element of the $employeeAges associative array:

The operator “=>” represents the relationship between a key and value. You can
imagine that the key points => to the value. In our example we name the key
$name and the value $age.

PHP Code:
————————————–
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";

foreach( $employeeAges as $name => $age )
{ echo “Name: $name, Age: $age <br>”; }

————————————–
Display:
Name: Lisa, Age: 28
Name: Jack, Age: 16
Name: Ryan, Age: 35
Name: Rachel, Age: 46
Name: Grace, Age: 34
————————–

 

Some more examples to demonstrate usages:

foreach example 1: value only

$a = array (1, 2, 3, 17);
foreach ($a as $v) {
echo "Current value of \$a: $v.\n";
}

/* foreach example 2: value (with key printed for illustration) */

$a = array (1, 2, 3, 17);
$i = 0; /* for illustrative purposes only */
foreach ($a as $v)
{
echo "\$a[$i] => $v.\n";
$i++;
}

/* foreach example 3: key and value */

$a = array (
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);


foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}

/* foreach example 4: multi-dimensional arrays */

$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";


foreach ($a as $v1)
{ foreach ($v1 as $v2)
{ echo "$v2\n"; }
}

/* foreach example 5: dynamic arrays */

foreach (array(1, 2, 3, 4, 5) as $v)
{ echo "$v\n"; }

Comments are closed.

We try to post all comments within 1 business day