PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<virtualarray_change_key_case>
view the version of this page
Last updated: Sat, 19 Apr 2003

II. Array Funktionen

Einf�hrung

Diese Funktionen erlauben es, Arrays auf verschiedene Arten zu manipulieren bzw. mit ihnen zu interagieren. Arrays sind wichtig, um Gruppen von Variablen zu verwalten, zu bearbeiten, oder zu speichern.

Es werden einfache und mehrdimensionale Arrays unterst�tzt, welche entweder vom Benutzer oder von einer anderen Funktion erstellt werden k�nnen. Es gibt bestimmte Datenbankfunktionen, welche die Ergebnisse aus Datenbankabfragen in Arrays speichern, und verschiedene andere Funktionen, die Arrays als R�ckgabewerte haben.

Im Abschnitt Arrays finden Sie eine detaillierte Erkl�rung, wie Arrays in PHP implementiert sind und wie sie benutzt werden.

Anforderungen

Diese Erweiterung ben�tigt zur Erstellung keine externen Bibliotheken.

Installation

F�r diese Funktionen ist keine Installation erforderlich, diese geh�ren zum Grundbestand von PHP.

Laufzeit Konfiguration

Diese Erweiterung definiert keine Konfigurationseinstellungen in der php.ini.

Resource Typen

Diese Erweiterung definiert keine Resource-Typen.

Vordefinierte Konstanten

Die aufgelisteten Konstanten stehen immer zur Verf�gung, da sie zum Grundbestand von PHP geh�ren.

CASE_LOWER (integer)

CASE_LOWER wird ben�tzt mit array_change_key_case() um die Schl�ssel von Arrays in Kleinbuchstaben umzuwandeln. Das ist auch der Standard f�r array_change_key_case().

CASE_UPPER (integer)

CASE_UPPER wird ben�tzt mit array_change_key_case() um die Schl�ssel von Arrays in Kleinbuchstaben umzuwandeln.

Siehe auch

Siehe auch is_array(), explode(), implode(), split(), preg_split() und join().

Inhaltsverzeichnis
array_change_key_case --  Liefert ein Array mit allen String-Schl�sseln in Klein- oder Gro�buchstaben
array_chunk -- Splittet ein Array in Teile auf
array_count_values -- Z�hlt die Werte eines Arrays
array_diff_assoc -- Computes the difference of arrays with additional index check
array_diff -- Ermittelt die Unterschiede von Arrays
array_fill -- F�llt ein Array mit Werten
array_filter --  Filtert Elemente eines Arrays mittels einer Callback-Funktion
array_flip -- Vertauscht Werte und Schl�ssel in einem Array
array_intersect_assoc -- Computes the intersection of arrays with additional index check
array_intersect -- Ermittelt die Schnittmenge von Arrays
array_key_exists -- Pr�ft, ob ein Schl�ssel in einem Array existiert
array_keys -- Liefert alle Schl�ssel eines Arrays
array_map --  Wendet eine Callback-Funktion auf die Elemente von Arrays an
array_merge_recursive --  F�hrt zwei oder mehr Arrays rekursiv zusammen
array_merge -- F�hrt zwei oder mehr Arrays zusammen
array_multisort -- Sortiert mehrere oder multidimensionale Arrays
array_pad --  Vergr��ert ein Array auf die spezifizierte L�nge mit einem Wert
array_pop -- Liefert das letzte Element eines Arrays
array_push --  F�gt ein oder mehr Elemente an das Ende eines Arrays
array_rand --  Liefert einen oder mehrere zuf�llige Eintr�ge eines Arrays
array_reduce --  Iterative Reduktion eines Arrays zu einem Wert mittels einer Callback Funktion
array_reverse --  Liefert ein Array mit umgekehrter Reihenfolge der Elemente
array_search --  Durchsucht ein Array nach einem Wert liefert bei Erfolg den Schl�ssel
array_shift --  Liefert ein Element vom Beginn eines Arrays
array_slice -- Extrahiert einen Ausschnitt eines Arrays
array_splice --  Entfernt einen Teil eines Arrays und ersetzt ihn durch etwas anderes
array_sum --  Liefert die Summe der Werte in einem Array
array_unique -- Entfernt doppelte Werte aus einem Array
array_unshift --  F�gt ein oder mehr Elemente am Anfang eines Arrays ein
array_values -- Liefert alle Werte eines Arrays
array_walk --  Wendet eine Benutzerfunktion an jedem Element eines Arrays an
array --  Erstellt ein Array
arsort --  Sortiert ein Array in umgekehrter Reihenfolge und beh�lt die Verbindung zum Index
asort --  Sortiert ein Array und beh�lt die Indexverbindungen
compact --  Erstellt ein Array mit Variablen und deren Werten
count -- Z�hlt die Elemente einer Variable
current -- Liefert das aktuelle Element eines Arrays
each --  Liefert das aktuelle Paar (Schl�ssel und Wert) eines Arrays und r�ckt den Array Cursor vor.
end --  Positioniert den internen Zeiger eines Arrays auf dessen letztes Element
extract --  Importiert Variablen eines Arrays in die aktuelle Symboltabelle
in_array -- Pr�ft, ob ein Wert in einem Array existiert
key --  Liefert einen Schl�ssel eines assoziativen Arrays
krsort --  Sortiert ein Array nach Schl�sseln in umgekehrter Reihenfolge
ksort -- Sortiert ein Array nach Schl�sseln
list --  Weist Variablen zu, als w�ren sie ein Array
natcasesort --  Sortiert ein Array in "nat�rlicher Reihenfolge", Gro�/Kleinschreibung wird ignoriert
natsort --  Sortiert ein Array in "nat�rlicher Reihenfolge"
next --  R�ckt den internen Zeiger eines Arrays vor
pos -- Liefert das aktuelle Element eines Arrays
prev --  Verkleinert den internen Zeiger eines Arrays
range --  Erstellt ein Array mit einem Bereich von Elementen
reset --  Setzt den internen Zeiger eines Arrays auf sein erstes Element
rsort --  Sortiert ein Array in umgekehrter Reihenfolge
shuffle -- Mischt die Elemente eines Arrays
sizeof -- Liefert die Anzahl Elemente einer Variable
sort -- Sortiert ein Array
uasort --  Sortiert ein Array mittels einer benutzerdefinierten Vergleichsfunktion und beh�lt Indexassoziationen bei.
uksort --  Sortiert ein Array nach Schl�sseln mittels einer benutzerdefinierten Vergleichsfunktion.
usort --  Sortiert ein Array nach Werten mittels einer benutzerdefinierten Vergleichsfunktion.


User Contributed Notes
Array Funktionen
add a note
david at preform dot dk
01-Feb-1999 01:30

use the max function to get the highest value of an array e.g:
  $maxval = max($array);

spinn at spinnwebe dot com
04-Apr-2001 10:58

I added this note to array_pop, but it's probably more applicable here:

If you use array_pop, the numeric indices  will be renumbered if there are any gaps. So if you start with

$a[5]="five";
$a[6]="six";

and then do array_pop($a), you now have $a[0]="five", not $a[5]="five", as you might expect. In other words, $a does not necessarily equal array_pop(array_push($a, 1)).

Response in the bug database was the following:

--
Presently, all splice-derived functions reorder numeric keys. There's not much to do about it, since it's the way Zend Engine handles numeric hash keys. Changing it either way won't bring more consistent  functionality, so in the meantime it is just as it is.
--

I'd disagree that changing my array indices is consistent, but there you are. I don't know which array functions are splice-derived, so look out for this.

jeroen at php dot net
29-Aug-2001 08:58

You should really read , there is a lot of info there about how to handle arrays, how to check wether indices are set, how to modify an array, anything.
mlong at mlong dot org
29-Jan-2002 10:55

You should pay attention to the fact that some functions act directly on the array (such as asort) and some don't touch the array but return a copy (such as array_reverse).  If you use one in the improper context you won't get a warning. It took me a while to notice this as I do a lot of coding by memory and don't refer to the function documentation unless I need to.
php dot net at chiefworks dot com
05-Feb-2002 06:56

To display the value of a variable from a two dimentional array inside a quoted string, use the following syntax:

<?php

$var = array(
   'name' => array(
       'first' => 'Caleb',
      'last' => 'Maclennan'
     )
 );

echo "My first name is {$var['name']['first']}!";

?>

bfair at logix3N0SPAM dot com
14-Apr-2002 10:34

Looping through an array, and printing each item:

for ($i = 0; $i < count($array_name); $i++) { echo("$i - $arrayname[$i]"); }

support at adventure-miami dot com
20-Apr-2002 01:43

You should pay attention to the fact that some functions act directly on
the array (such as asort) and some don't touch the array but return a copy
(such as array_reverse).

Tim Burly

josh at mirtec dot net
29-May-2002 03:17

here's a little function i wrote to convert any multidimensional array to an xml tree. it has this prototype:

string arr2xml (array array, [string tree_name], [[int level])

use the second argument if you want to specify a name for the top of the tree - otherwise it defaults to level0. the first call to the function is kind of a dummy top level that wraps the array inside another array and calls the function for real.

dont use the third argument. thats used to keep track of the levels in all the recursive calls.

heres the code:

function arr2xml ($arr)
{
  if (func_num_args () < 3)
  {
     $wrapper = (func_num_args < 2) ? array ($arr) : array (func_get_arg(1)=>$arr);
     $xml = arr2xml ($wrapper, '', 0);
  }
  else
  {
     $level = func_get_arg (2);
     while (list ($key, $val) = each ($arr))
     {
      if ($key === (int)$key) $key = 'level'.$level;
        $xml .= '<'.$key.'>';
        if (gettype ($val) == 'array')
       {
           $xml .= arr2xml ($val, '', $level+1);
        }
           else
        {
           $xml .= $val;
       }
        $xml .= '</'.$key.'>';
     }
  }
  return $xml;
}

bishop
07-Jun-2002 06:42

Sometimes you need an array that has all keys exactly equal to all values. For example, arrays that look like:
array('a' => 'a', 'b' => 'b', 'c' => 'c');

You can either do it manually (a pain for count($a) > 2), or use array_smear():

/* smear values across into keys, or vice-versa */
function array_smear($a, $v2k = true) {
   $values = ($v2k) ? array_values($a) : array_keys($a);

   $a = array();
  foreach ($values as $v)
       $a[$v] = $v;

   return ($a);
}

array_smear takes an array, then a boolean specifying whether you want to smear the values over into the keys (the default, and probably what you usually want) or vice-versa.

So:
$a = array('a', 'b', 'c');

$x = array_smear($a);
// x == array('a' => 'a', 'b' => 'b', 'c' => 'c');

$y = array_smear($a, false);
// y == array(0 => 0, 1 => 1, 2 => 2);

spam (at) speedcapture . com
15-Jun-2002 02:50

I want to share a VERY usefull way to debug php and arrays:

just create a file like array.func.inc.php

paste the following code into the file.

// To make ANY array visible ...

function viewArray($arr)
{
   echo '<table cellpadding="0" cellspacing="0" border="1">';
   foreach ($arr as $key1 => $elem1) {
       echo '<tr>';
       echo '<td>'.$key1.'&nbsp;</td>';
       if (is_array($elem1)) { extArray($elem1); }
       else { echo '<td>'.$elem1.'&nbsp;</td>'; }
       echo '</tr>';
   }
   echo '</table>';
}

function extArray($arr)
{
   echo '<td>';
   echo '<table cellpadding="0" cellspacing="0" border="1">';
   foreach ($arr as $key => $elem) {
      echo '<tr>';
       echo '<td>'.$key.'&nbsp;</td>';
       if (is_array($elem)) { extArray($elem); }
       else { echo '<td>'.htmlspecialchars($elem).'&nbsp;</td>'; }
      echo '</tr>';
   }
   echo '</table>';
   echo '</td>';
}

close the file and include that file into any other php document. If u want to check the content of an array just type viewarray($array);

webkid%webkid.com
19-Jun-2002 06:47

A painstakenly written function to add a "value" to a recursive array using a pathlist (also in the format of an array):

function recurse($a,$rm,$k,$d){ if (sizeof($rm)==0){$a[$k]=$d;
return ($a);}
$sh=array_shift($rm); $a[$sh]=recurse ($a[$sh],$rm,$k,$d);
return ($a);}

Called like this: $ary=recurse($ary, array("level1","level2","level3"),"key",$value);

So an array like
Array(
   [0] => a
   [1] => b
   [2] => c
   [d] => Array
       (   [0] => a
          [1] => b
           [c] => Array
               (   [0] => e
                   [1] => f
                   [2] => g
                   [3] => h
                   [i] => Array
                       (   [0] => n
                      ) ) ) )
Can become
Array(
   [0] => a
   [1] => b
   [2] => c
   [d] => Array
       (   [0] => a
          [1] => b
           [c] => Array
               (  [0] => e
                   [1] => f
                  [2] => g
                   [3] => h
                   [i] => Array
                       (   [0] => n
                          [key] => data
                       ) ) ) )
With the call
$ary=recurse($ary,array("d","c","i"),"key","data");

b dot parish at linst dot ac dot uk
21-Jun-2002 06:14

<?

$myarray = array();

$myarray[1] = 1;
$myarray[2] = 2;
$myarray[3] = 3;
$myarray[4] = 4;

// I want to move $myarray[2] to the 4th position.

$ordered_array = reposition($myarray, 2,4);

foreach($ordered_array as $key=>$value){
echo "ordered_array[$key] = $value";
}

?>

// The output of this function will be:

ordered_array[1] = 1
ordered_array[2] = 4
ordered_array[3] = 2
ordered_array[4] = 3

<?

function reposition($myarray,$myarray_key,$newpos){

$oldpos = $myarray[$myarray_key];

foreach($myarray as $key=>$value){
if($key==$myarray_key){
$myarray[$key] = $newpos;
}else{

if($oldpos>=$newpos){  // It's moving up the array

// Values following it will go down (lower position)

if($myarray[$key]<=$oldpos && $myarray[$key]>=$newpos){
$myarray[$key]++;
}

}else{ // It's moving down the array

// Values preceding it will go up (higher position)

if($myarray[$key]>=$oldpos && $myarray[$key]<=$newpos){
$myarray[$key]--;
}
}
}
}
return $myarray;
}

?>

michael at ettl dot co dot at
29-Jul-2002 01:31

CSS-Parsing Function with associative array and PREG - splitting.
You can fetch CSS-Tags with

$aCSS=parseCSS("style.css");
echo $aCSS["body"]["background-color"];

function parseCSS($filename)
{
$fp=fopen($filename,"r");
$css = fread($fp, filesize ($filename));
fclose($fp);

$css=preg_replace("/[\s,]+/","",$css);
$css_class = preg_split("/}/", $css);

while (list($key,$val) = each ($css_class))
{
  $aCSSObj=preg_split("/{/",$val);
  $a=preg_split("/;/",$aCSSObj[1]);
  while(list($key,$val0) = each ($a))
   {
 if($val0 !='')
{
      $aCSSSub=preg_split("/:/",$val0);
      $aCSSItem[$aCSSSub[0]]=$aCSSSub[1];
     }
   }
  $aCSS[$aCSSObj[0]]=$aCSSItem;
  unset($aCSSItem);
}

unset($css);
unset($css_class);
unset($aCSSSub);
unset($aCSSItem);
unset($aCSSObj);

return $aCSS;
}

dan at kuykendall dot org
23-Aug-2002 10:56

Here is my var2xml function.
This one will convert any var type except objects, and for arrays it will take indexed subarrays and assume they should be duplicates of the parent tag name.

function var2xml ($name, $value, $indent = 1)
{
 $indentstring = $this->indentstring;
 for ($i = 0; $i < $indent; $i++)
{
   $indentstring .= $this->indentstring;
 }
 if (!is_array($value))
 {
   $xml = $indentstring.'<'.$name.'>'.$value.'</'.$name.'>'."\n";
}
 else
 {
   if($indent === 1)
   {
     $isindex = False;
   }
   else
   {
     $isindex = True;
    while (list ($idxkey, $idxval) = each ($value))
     {
       if ($idxkey !== (int)$idxkey)
       {
         $isindex = False;
      }
     }
   }
   
   reset($value);  
   while (list ($key, $val) = each ($value))
   {
     if($indent === 1)
     {
       $keyname = $name;
       $nextkey = $key;
    }
     elseif($isindex)
     {
       $keyname = $name;
       $nextkey = $name;
     }
     else
    {
       $keyname = $key;
       $nextkey = $key;
    }

     if (is_array($val))
     {
       $xml .= $indentstring.'<'.$keyname.'>'."\n";
       $xml .= $this->var2xml ($nextkey, $val, $indent+1);
       $xml .= $indentstring.'</'.$keyname.'>'."\n";
     }
    else
     {
       $xml .= $this->var2xml ($nextkey, $val, $indent);
     }
   }
 }
 return $xml;
}

J. Dyer (jkdyer_at_vlsmaps_dot_com)
10-Sep-2002 09:55

As it has been stated before, array_pop and the splice-derived functions re-index any associatively defined elements..

// bad array example
$array[5] = "foo";
$array[6] = "bar";
$var = array_pop($array);
$key = key($array);
// $key would be 0, not 5 as would be expected for the value "foo".

Instead, keep your keys/associations by using the unset() function.

// better array example
end($array);
$key = key($array);
unset($array[$key]);
// now the other keys/values aren't touched.

... This will remove the last entry in your array, but not re-index it.  In this manner, you won't lose your associations. It has been tested and seems to work fine.

ifrostNOSPAM at uos dot de
14-Sep-2002 05:59

A simple way to print the structure and the values of an array:

echo '<pre>';
print_r($my_array);
echo '</pre>';

adam dot swick at NOSPAM dot pantellos dot com
21-Sep-2002 08:03

Multidimensional lookup sample

db table
==================
name.....type
-----....-------
Judy.....Brunette
Jackie...Blonde
Jill.....Redhead

code
===================
$key = 0;  
while ($row=mssql_fetch_array($result)) {
  $TPType["Name"][$key] = $row["name"];
  $TPType["Type"][$key] = $row["type"];
$key++;
  }

$searchName = "Jill";
 $key = array_search ($searchName, $TPType["Name"]);
$searchName .= " (".$TPType["Type"][$key].")";

results
===============
Jill (Redhead)

contact at chezjulien . com
26-Sep-2002 01:33

If you want to delete a value from an array, here's a function which will suit your needs:

<pre>
function array_delete_value($array, $value) {
for($i=0;$i<count($array);$i++) {
if ($array[$i] == $value) unset($array[$i]);
if(!isset($array[$i])) {
$array[$i] = $array[$i+1];
unset($array[$i+1]);
}
}
return $array;
}
</pre>

Hope this helps,

Julien, from France

atnak at chejz dot com
26-Nov-2002 07:12

Here's a function that will set an arbitary array field to an arbitary value:

function array_field_to_value(&$array, $field, $value)
{
   if ( is_array($field) )
   {
       $head = array_shift($field);

       if ( count($field) == 0 )
      {
           $array[$head] = $value;
       }
       else
     {
           array_field_to_value($array[$head], $field, $value);
       }
   }
   else
   {
      $array[$field] = $value;
   }
}

I find this useful for doing things like this:

$post_arg = "1,10,pizza,orange,cat";
$post_val = "something";

$myarray = array();
array_field_to_value($myarray, explode(',', $post_arg), $post_val);

Which gets the same results as doing:

$myarray = array();
$myarray['1']['10']['pizza']['orange']['cat'] = "something";

mailman(AT)hit-squad.net
05-Dec-2002 01:30

I noticed a lack of a function to insert a value into a specified place in an array.  Here'a a function I came up with that will do this:

function array_insert(&$array, $value, $pos)
{
    if (!is_array($array))
         return FALSE;

    $last = array_splice($array, $pos);

    array_push($array, $value);
    $array = array_merge($array, $last);
}

It can be used like this:

$a = array("zero", "one", "two", "three", "four", "five", "six", "seven", "eight");
array_insert($a, "POOP", 4);

The array will now contain:
("zero", "one", "two", "three", "POOP", "four", "five", "six", "seven", "eight")

wheaty at planetquake dot com
17-Dec-2002 01:34

In keeping with OO principles in PHP4, if you want to pass a reference of an array to an object (instead of using ugly global variables):

==================================
class A
{
  var $myarray;

    // constructor
    function A ( &$array_param )
    {
         $this->myarray =& $array_param;
    }

    function put_hi()
    {
       $this->myarray[] = "Hi!";
    }
}

$greetings = array("Hello.", "How are you doing?", "What's up?");

$myobj =& new A($greetings);
$myobj->put_hi();

print_r($greetings);
==================================

Will Output:

Array ([0] => Hello. [1] => How are you doing? [2] => What's up? [3] => Hi!)

mno11 at lycos dot NOSPAM
27-Dec-2002 10:41

For those that would like something similar to print_r, but instead returns the values as a string, I've written the following simple function. It doesn't work for 3D arrays, yet...

 function arrayData($array)
{
     $keys = array_keys($array);
     $values = array_values($array);

     $data = "";
     for ($i=0; $i<count($keys); $i++)
     {
         $data .= $keys[$i]."=>'".$values[$i]."' , ";
    }

     return $data;
 }

To email me, replace NOSPAM with com

jon at pixelmajik dot com
30-Dec-2002 08:10

A little function which rotates a 2d array (or, basically, swaps the first two keys of a multidimensional array).  Oh, and it's hash-friendly (hence my use of foreach instead of for).

Example 1:
$a['alice']['gender'] = 'f';
$a['alice']['status'] = 'single';
$a['bob']['gender'] = 'm';
$a['bob']['status'] = 'married';
$a['charles']['gender'] = 'm';
$a['charles']['status']='divorced';
$b = array_rotate_2d($a);

print_r($b) results in:

Array
(
 [gender] => Array
       (
           [alice] => f
          [bob] => m
           [charles] => m
       )

  [status] => Array
       (
           [alice] => single
           [bob] => married
           [charles] => divorced
       )
)

As you may see, it's useful for displaying rows as columns (example 2, below) or reorganizing data (example 1, above).

Example 2:
$qid = mysql_query("SELECT ... FROM table");
while($row = mysql_fetch_array($qid, MYSQL_ASSOC))
  $table[] = $row;
$rotated_table = array_rotate_2d($table);
foreach($table AS $row) { echo join("\t", $row)."\n"; }

Code:
function array_rotate_2d($old)
{
 // rotates a 2d array such that $array[$i][$j] becomes $array[$j][$i].  (useful for displaying rows as columns, for example)

 foreach($old AS $k1=>$v1)
  foreach($v1 AS $k2=>$v2)
     $new[$k2][$k1] = $v2;

 return $new;
}

philNOSPAMippe at moNO-SPAMrange dot n-e-t
08-Jan-2003 03:35

Hi,
I took the function from spam (at) speedcapture . com
I simplified it just a little, and here is the result.
Thanks for sharing this great tool with us. Simple, but sooooo usefull :)

function view_array($arr, $td=0)
{
   if ($td) {
       echo '<td>';
   }
   echo '<table>';
   foreach ($arr as $key => $elem) {
       echo '<tr>';
       echo '<td>'.$key.'&nbsp;</td>';
       if (is_array($elem)) {
           view_array($elem, 1);
       }
       else {
           echo '<td>'.htmlspecialchars($elem).'&nbsp;</td>';
        }
       echo '</tr>';
   }
   echo '</table>';
   if ($td) {
       echo '</td>';
  }
}

You call it as you used to:
Let $myArray be an array of any kind,
simply do view_array($myArray);

brian at exclamationlabs dot com
10-Jan-2003 11:47

Frederic Maybaum in newsgroups gave me this solution.
If you are coming from perl and want to get the -1, -2, etc of an array, you don't have this convention in PHP, there is no $array[-1].

So here are 2 solutions:

$stuff  = array('lard','utensil','pig','roasting spit');

to get 'roasting spit' you can do this:
print end($stuff) ."\n";

If your looking for something a little more flexible:
print $stuff[count($stuff) - 1] ."\n"; // 'roasting spit'
print $stuff[count($stuff) - 2] ."\n"; // 'pig'

This is handy if you are looking for a quick method to grab a filename from a fully qualified filename variable:

$filename = "/usr/local/proggy/bin/goober";
print end(preg_split("|\/|",$filename)) ."\n"; // <-- goober

Thanks Frederic!

jan at vanhaarst dot net
31-Jan-2003 03:55

Without recursive programming, you would do it like this, to get all info from a 3D associative array:

<pre>
<?
//print_r ($contig);
?>
<?
foreach($contig as $key_val =>$value) {
 if (is_array($value)) {
   echo "
<b>$key_val</b>";
   foreach($value as $key_val2 =>$value2) {
     if (is_array($value2)) {
      echo "
<b>$key_val2</b>";
      foreach($value2 as $key_val3 =>$value3) {
         echo "
$key_val3 = $value3";
       }
     }else{
     echo "
$key_val2 = $value2";
     }
   }
}else{
   echo "
$key_val = $value";
}
}
?>
</pre>

rafael dot lima at pobox dot com
07-Feb-2003 08:21

Two magical functions to be included in all projects!

function imp($var)
{
  echo '<xmp>';
  print_r($var);
  echo '</xmp>';
}

function br($var)
{
  echo '< br>'.$var.</ br>';
}

telefoontoestel at officexpert dot digitaal dot biz
12-Feb-2003 06:13

I've created a small function for the optimization of an array. It removes all empty elements and sets the next filled element to the place the empty element was. It is a function wich argument is passed by reference, so it will only return true, in case the value of the argument was correct or false if the value was incorrect.

function arOpt(&$array){ // pass by reference
       if(!is_array($array)){
              return false;
       }
       $temp; // create a temporary array;
       for($i = 0; $i < sizeof($array); $i++){
              if(!empty($array[$i])){
                      $temp[sizeof($temp)] = $array[$i];
               }
       }
       $array = $temp;
       return true;
}

programming at shrum dot net
14-Feb-2003 08:50

Using a foreach loop vs. a for loop

This may be a better way to traverse an associative array:

 foreach (array_keys($array_name) as $key) {
     echo($array_name[$key] . "
");
}

In case anybody is wondering.

josh NO at SPAM mirtec dot net
17-Feb-2003 05:05

Instant JavaScript array from PHP array (any combination of associative / numeric sub-arrays):

function arrayToJS ($theArray, $jsArrayName)
{
   $jsArrayString = $jsArrayName . " = new Array ();\n";
   foreach ($theArray as $key => $val)
  {
       if (is_numeric ($key))
       {
           $jsElement = $key;
       }
       else
       {
          $jsElement = '\'' . $key . '\'';
       }

       if (is_array ($val))
       {
       $jsArrayString .= arrayToJS ($val, $jsArrayName . '[' . $jsElement . ']');
       }
       else
      {
           if (is_numeric ($val))
           {
             $jsValue = $val;
           }
           else
          {
               $jsValue = '\'' . $val . '\'';
           }
         
           $jsArrayString .= $jsArrayName . '[' . $jsElement . '] = ' . $jsValue . ";\n";
       }
   }
   
  return $jsArrayString;
}

//----------------usage------------------//

echo '<script language="JavaScript" type="text/javascript">';
echo arrayToJS ($myArray, 'myJSArray');
echo '</script>';

// for some reason the PHP site keeps scrambling my indentation .. :(

Frank
09-Mar-2003 11:34

After doing a lot of research i discovered that multidimensional arrays did not work as some people explained.

Suppose the table "Projecten" contains:
project_id,project_omschrijving
1,first
2,second

And using the next code

$proj_result = pg_query("SELECT * FROM \"Projecten\"")
or die (pg_last_error());

if ($myrow = pg_fetch_array($proj_result)) {
do {
$proj[][0]=$myrow["project_id"];
$proj[][1]=$myrow["project_omschrijving"];
} while ($myrow = pg_fetch_array($proj_result));
}

Would create an array:
$proj[0][0]=1
$proj[0][1]=first
$proj[1][0]=2
$proj[1][1]=second

I would then expect foreach( $proj as $s) to give me:
$s as an array containing(1,first)
and the next foreach loop would give me an array $s=(2,second). But this is not working here. It returns (first)

So be carefull when using foreach and the other walkers of arrays when using mutliple dimension arrays.

Be prepared to walk value by value and act accordingly.

This took me sometime to figure out.

rudecoder at yahoo dot com
25-Mar-2003 04:52

Here's a tested function that will help you swap array elements  with minimal effort.

function reposition($myarray,$oldpos,$newpos){

       $temparray = $myarray;
       
       for($i=0; $i < count($myarray); $i++){
             if($i == $oldpos){
                  $temparray[$newpos] = $myarray[$i];
             }
            if($i == $newpos){
                  $temparray[$oldpos] = $myarray[$i];
             }
        }
        return $temparray;
}

// Example of use...

$most_popular = array("Seineld","Elaine","Kramer","George");

// Now let's make Elaine more popular then Kramer
$most_popular = reposition($most_popular,3,1);

//Now we have an array with Elaine and George in swapped positions:
//$most_popular[0] = "Seinfeld";
//$most_popular[1] = "George";
//$most_popular[2] = "Kramer";
//$most_popular[3] = "Elaine";

alban dot medici at fr dot netcentrex dot net
26-Mar-2003 04:18

If you want to simply remove a couple (key - value) from an indexes array , use the unset function as :

$yourArray = array("Key1" => toto,
                         "key2"  => titi,
                        "badKey" => value);

// you make your treatment and whant to remove the badKey
// cause not useful anymore ...

unset($yourArray[badKey]);

//then your array look like this :
$yourArray[Key1] = toto
$yourArray[key2]  = titi

didi at example dot com
15-Apr-2003 05:06

One good book for getting started is PHP FAST & EASY WEB DEVELOPMENT, 2ND EDITION, by JULIE C. MELON. The publishers added to the 2nd Edition three beginning chapters that detailed, easy-to-follow download/setup instructions for MySQL, Apache Web Server, and PHP respectively on both Windows and Linux. Too many beginning programming books assume you've already got your development environment setup, so this book was a breath of fresh air for me as I took up PHP for the first time.
jmoponfire at hotmail dot com
27-Apr-2003 10:03

Removing Duplicate elements

A function that takes a indexed one-dimensional array and returns an array containing the unique values of the first array:

function removeduplicates($x)
{
   $i = sizeof($x);
   if($i>1)
   {
       $q=0;
       $y = array();
       $z = array();
       for($k=0;$k<$i-1;$k++)
      {
           $flag = 0;
          for($j=$k+1;$j<$i;$j++)
           {
               if($x[$k] == $x[$j])
               {
                   $flag=1;
             }
           }
           $y[$k] = $flag;
       }
      $y[$i-1] = 0;
       $j=0;
      for($k=0;$k<$i;$k++)
       {
           if($y[$k]!= 1)
          {
               $z[$j] = $x[$k];
               $j++;
         }
       }
   }
   else
       $z=$x;
  return $z;
}

28-Apr-2003 01:55
this simple function will append array $a2 to array $a1 and return the total number of elements added

function array_append(&$a1, $a2)
{
if( !is_array($a1) || !is_array($a2) )
return 0;

foreach( $a2 as $val )
$a1[] = $val;

return count($a2);
}

Ex:
$arr = array(1,2,3,4);
array_append($arr, array(5,6,7,8));
print_r($arr);
Output
------
Array
(
  [0] => 1
   [1] => 2
   [2] => 3
   [3] => 4
 [4] => 5
   [5] => 6
   [6] => 7
   [7] => 8
)

brian at stkinternational dot com
02-May-2003 03:10

I needed an easy way to move around the internal pointer of an array in place.  Here are a couple of functions that I put together out of necessity.

/**
* @return void
* @param $array array
* @param offset int
* @desc Set internal array pointer to absolute offset
*/
function aseek(&$array, $offset)
{
 if ( $offset >= 0 )
  {
   reset($array);
   while (--$offset > 0)
    {
     next($array);
    }
  }
 else
  {
   end($array);
   while (++$offset < 0)
    {
    prev($array);
    }
  }
}

/**
* @return void
* @param $array array
* @param offset int
* @desc Set internal array pointer to relative offset
*/
function rseek(&$array, $offset)
{
 if ($offset > 0)
  {
   while ($offset-- > 0)
    {
     next($array);
    }
  }
 else
  {
   while ($offset++ < 0)
    {
     prev($array);
    }
  }
}

add a note

<virtualarray_change_key_case>
 Last updated: Sat, 19 Apr 2003
show source | credits | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: /
Last updated: Mon May 12 21:12:21 2003 CEST