suche nach in der

array_change_key_case> <Sorting Arrays
Last updated: Sat, 07 Jan 2012

view this page in

Array Funktionen

Siehe auch

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

Inhaltsverzeichnis

  • array_change_key_case — Ändert alle Schlüssel in einem Array
  • array_chunk — Splittet ein Array in Teile auf
  • array_combine — Erzeugt ein Array, indem es ein Array für die Schlüssel und ein anderes für die Werte verwendet
  • array_count_values — Zählt die Werte eines Arrays
  • array_diff_assoc — Berechnet den Unterschied zwischen Arrays mit zusätzlicher Indexprüfung
  • array_diff_key — Berechnet den Unterschied zwischen Arrays, indem es die Schlüssel vergleicht
  • array_diff_uassoc — Berechnet den Unterschied von Arrays mit zusätzlicher Indexprüfung, welche durch eine benutzerdefinierte Funktion vorgenommen wird
  • array_diff_ukey — Berechnet den Unterschied zwischen Arrays mittels einer Callbackfunktion für den Vergleich der Schlüssel
  • array_diff — Ermittelt die Unterschiede zwischen Arrays
  • array_fill_keys — Befüllt ein Array mit Werten mit den übergebenen Schlüsseln
  • array_fill — Füllt ein Array mit Werten
  • array_filter — Filtert Elemente eines Arrays mittels einer Callback-Funktion
  • array_flip — Vertauscht alle Schlüssel mit ihren zugehörigen Werten in einem Array
  • array_intersect_assoc — Ermittelt die Schnittmenge von Arrays mit Indexprüfung
  • array_intersect_key — Ermittelt die Schnittmenge von Arrays, indem es die Schlüssel vergleicht
  • array_intersect_uassoc — Ermittelt die Schnittmenge von Arrays mit Indexprüfung; vergleicht Indizes mit einer Callbackfunktion
  • array_intersect_ukey — Ermittelt die Schnittmenge zweier Arrays mittels eines durch eine Callbackfunktion durchgeführten Schlüsselvergleiches
  • 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 oder eine Teilmenge aller Schlüssel eines Arrays
  • array_map — Wendet eine Callback-Funktion auf die Elemente von Arrays an
  • array_merge_recursive — Führt ein oder mehrere Arrays rekursiv zusammen
  • array_merge — Führt ein oder mehrere 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_product — Ermittelt das Produkt von Werten in einem Array
  • 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 Callbackfunktion
  • array_replace_recursive — Replaces elements from passed arrays into the first array recursively
  • array_replace — Replaces elements from passed arrays into the first array
  • array_reverse — Liefert ein Array mit umgekehrter Reihenfolge der Elemente
  • array_search — Durchsucht ein Array nach einem Wert und liefert bei Erfolg den zugehörigen 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_udiff_assoc — Ermittelt den Unterschied zwischen Arrays mit zusätzlicher Indexprüfung, vergleicht mittels einer Callbackfunktion
  • array_udiff_uassoc — Ermittelt den Unterschied zwischen Arrays mit zusätzlicher Indexprüfung, vergleicht Daten und Indizes mittels einer Callbackfunktion
  • array_udiff — Ermittelt den Unterschied zwischen Arrays mittels einer Callbackfunktion für den Datenvergleich
  • array_uintersect_assoc — Ermittelt die Schnittmenge von Arrays mit zusätzlicher Indexprüfung, vergleicht Daten mittels einer Callbackfunktion
  • array_uintersect_uassoc — Ermittelt die Schnittmenge von Arrays mit zusätzlicher Indexprüfung, vergleicht Daten und Schlüssel mittels einer Callbackfunktion
  • array_uintersect — Ermittelt die Schnittmenge von Arrays, vergleicht Daten mittels einer Callbackfunktion
  • 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_recursive — Wendet eine Benutzerfunktion rekursiv auf jedes Element eines Arrays an
  • array_walk — Wendet eine Benutzerfunktion auf jedem Element eines Arrays an
  • array — Erstellt ein Array
  • arsort — Sortiert ein Array in umgekehrter Reihenfolge und erhält die Index-Assoziation
  • asort — Sortiert ein Array und erhält die Index-Assoziation
  • compact — Erstellt ein Array mit Variablen und deren Werten
  • count — Zählt alle Elemente eines Arrays oder Attribute eines Objekts
  • current — Liefert das aktuelle Element eines Arrays
  • each — Liefert das aktuelle Paar (Schlüssel und Wert) eines Arrays und rückt den Arrayzeiger 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 — Alias von current
  • prev — Setzt den internen Zeiger eines Arrays um ein Element zurück
  • 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 — Alias von count
  • 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


add a note add a note User Contributed Notes
Array Funktionen
phamphong_tn at yahoo dot com
29-Jun-2007 01:34
This is a code remove an other row of array
<?php
//$mang is an array, $id is index of row in array
function remove($mang,$id)
{
   
$flag    =    false;
   
$count    =    count($mang);
   
$i    =    0;
    while (
$flag!=true && $i<$count) {
        if (
$i==$id) {
            unset(
$mang[$i]);
           
$flag    =    true;
           
$index    =    $i;
        }
        else {
            if (
$temp) {
               
array_push($temp,$mang[$i]);
            }
            else
            {
               
$temp    =    array($mang[$i]);
            }
        }
       
$i++;
    }
    if (
$flag) {
        while (
$index<$count)
        {
            if (
$temp) {
               
array_push($temp,$mang[$index+1]);
            }
            else
            {
               
$temp    =    array($mang[$index+1]);
            }
           
$index++;
        }
    }
   
array_pop($temp);
    return
$temp;
}

$arr    =    array(array("id"=>"1","name"=>"b"),array("id"=>"2","name"=>"d"));
array_push($arr,array("id"=>"3","name"=>"f"));
array_push($arr,array("id"=>4,"name"=>"g"));
$arr = remove($arr,2);
echo
"<pre>";
print_r($arr);
?>
peanutpad at msn dot com
16-Jun-2007 12:15
heres a function from http://www.linksback.org  Feedback welcome, of course!  Public domain, yadda yadda.

function mySort(&$array,$key) {
    if (!is_array($array) || count($array) == 0) return true;
    $assocSortCompare  = '$a = $a["'.$key.'"]; $b = $b["'.$key.'"];';

    if (is_numeric($array[0][$key])) {
      $assocSortCompare.= ' return ($a == $b) ? 0 : (($a < $b) ? -1 : 1);';
    } else {
      $assocSortCompare.= ' return strcmp($a,$b);';
    }

    $assocSortCompare = create_function('$a,$b',$assocSortCompare);
    return usort($array,$assocSortCompare);
}
webdev at svbeatrix dot com
11-Jun-2007 06:06
Bugs happen, but how can people post functions that WON'T EVEN COMPILE!  I truly detest finding a cool code snippet or function and then having to debug them. Sorry for the rant, but I have experienced this scenario a number of times.  TEST YOUR CODE, THEN POST!

Here is a revised and corrected previously posted function ArrayDepth, which had 3 bugs and yes, would not compile.

function ArrayDepth($Array,$DepthCount=-1) {
// Find maximum depth of an array
// Usage: int ArrayDepth( array $array )
// returns integer with max depth
// if Array is a string or an empty array it will return 0
  $DepthArray=array(0);
  $DepthCount++;
  $Depth = 0;
  if (is_array($Array))
    foreach ($Array as $Key => $Value) {
      $DepthArray[]=ArrayDepth($Value,$DepthCount);
    }
  else
    return $DepthCount;
  return max($DepthCount,max($DepthArray));
}
sean at aliencreations dot com
10-Jun-2007 01:36
I wrote this function to parse arrays so they work with SQL strings if you need to use the MySQL "IN()" function.

function format_sql_array($array)
{
    $SQLstring = "";
    foreach($array as $item)
      {
        $SQLstring .= "'$item',";
      }
    $SQLstring = rtrim($SQLstring, ",");
    $SQLstring = str_replace("'',", "", $SQLstring);
    return $SQLstring;
}

Example:
$my_array = array("red", "blue", "green");
$sql_array = format_sql_array($my_array);
//$sql_array is now "'red','blue','green'"

Sample SQL:
$SQL = "SELECT FROM colors_table WHERE color IN($sql_array)";
sid dot pasquale at gmail dot com
29-May-2007 11:57
<?php
/* This function allow you to transform a multidimensional array
   in a simple monodimensional array.
   Usage: array_walk($oldarray, 'flatten_array', &$newarray);
   For example, this code below shows to you:
        Array
        (
            [1] => Array
                (
                    [0] => 1
                    [1] => 2
                )
       
            [2] => Array
                (
                    [0] => 3
                    [1] => 4
                )
       
        )
       
        Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
        )
*/

function flatten_array($value, $key, &$array) {
    if (!
is_array($value))
       
array_push($array,$value);
    else
       
array_walk($value, 'flatten_array', &$array);
 
}
 
$oldarray = array(
   
1 => array(1,2),
   
2 => array(3,4)
);
$newarray = array();
array_walk($oldarray, 'flatten_array', &$newarray);
echo
"<pre>";
print_r($oldarray);
print_r($newarray);
echo
"</pre>";
?>
djspy187 at gmail dot com
16-May-2007 11:05
I had an issue with arrays and copying them by reference as follows.

    // Loop on the list and insert default values
    foreach ($navigation as &$item)
    {       
        $children = &$item['children']};

        foreach ($children as &$child)
        {
         // Do stuff
        }
    }

This would give me error message

Fatal error: Cannot create references to/from string offsets nor overloaded objects in /var/www/dev/kh_system/navigation.php on line 103

Even though $item['children'] is an array.

The workaround is to do a for ($i =0;$i < count($Item);$i++) and to then access the children like this

$navigation[$i]['children']
frando
26-Apr-2007 04:14
This is a super-hard array conversion function.
It only returns TRUE if the two arrays are completely identical, that means that they have the same keys, and the values of all keys are exactly the same (compared with ===).

<?php
function array_same($a1, $a2) {
  if (!
is_array($a1) || !is_array($a2))
    return
false;
 
 
$keys = array_merge(array_keys($a1), array_keys($a2));
 
  foreach (
$keys as $k) {
    if (!isset(
$a2[$k]) || !isset($a1[$k]))
      return
false;
     
    if (
is_array($a1[$k]) || is_array($a2[$k])) {
      if (!
array_same($a1[$k], $a2[$k]))
        return
false;
    }
    else {
      if (! (
$a1[$k] === $a2[$k]))
        return
false;
    }
  }
 
  return
true;
}
?>
Q1712 at online dot ms
23-Apr-2007 03:34
for your intrest:
the values of the constans used are (all integer):

CASE_LOWER = 0
CASE_UPPER = 1
SORT_ASC = 4
SORT_DESC = 3
SORT_REGULAR = 0
SORT_NUMERIC = 1
SORT_STRING = 2
SORT_LOCALE_STRING = 5
COUNT_NORMAL = 0
COUNT_RECURSIVE = 1
EXTR_OVERWRITE = 0
EXTR_SKIP = 1
EXTR_PREFIX_SAME = 2
EXTR_PREFIX_ALL = 3
EXTR_PREFIX_INVALID = 4
EXTR_PREFIX_IF_EXISTS = 5
EXTR_IF_EXISTS = 6
EXTR_REFS = 256
info at dyflexis dot nl
17-Apr-2007 10:13
A modernized version of the flatten_array() functies written by

davidj at boundlessgallery dot DISLIKESPAM dot com
on 02-Apr-2004 03:10

This function is able to work with associative arrays

<?php
function flatten_array($array) {
    
$size=sizeof($array);
    
$keys=array_keys($array);
    for(
$x = 0; $x < $size; $x++) {
        
$element = $array[$keys[$x]];

        if(
is_array($element)) {
           
$results = flatten_array($element);
               
$sr = sizeof($results);
               
$sk=array_keys($results);
            for(
$y = 0; $y < $sr; $y++) {
               
$flat_array[$sk[$y]] = $results[$sk[$y]];
            }
        } else {
           
$flat_array[$keys[$x]] = $element;
        }
    }

    return
$flat_array;
}
?>
psbrogna at yahoo dot com
17-Apr-2007 05:12
Why is a deep copy function needed to move a sub array? I've just used the equality operator as in the code below.

<?php

$a
= array(
   
'a'=>'apple',
   
'b'=>'banana',
   
'c'=>'cherry',
   
'subArray'=>array(
     
'A'=>'APPLE',
     
'B'=>'BANANA',
     
'C'=>'CHERRY'
   
)
  );

$a['copiedArray']= $a['subArray']; unset($a['subArray']);

var_dump($a);

?>

The above outputs the $a array with copiedArray being present and subArray gone. (php version: 4.4.0).
wmakend at intershop dot de
05-Apr-2007 11:41
if you want to sort array like this one
$aInt = array('1','2','3','4');
and you to have somethings like this
1 --- 2
1 --- 3
1 --- 4
2 --- 3
2 --- 4
3 --- 4

you can do this like with

$NumInt = count($aInt);
for($j=0; $j<=$NumInt-1; $j++){       
        $first = $aInt[$j];
            for ($i=1; $i<=$NumInt-1-$j; $i++) {
                echo $first." --- ".$aInt[$i+$j]."<br>";
            }     
}
info at joolee dot nl
19-Mar-2007 01:49
A slight modification in the arraytostring function, posted below. This function lists an array the same way you would define it in PHP.

<?PHP
function arraytostring($array, $depth = 0)
{
   if(
$depth > 0)
     
$tab = implode('', array_fill(0, $depth, "\t"));
  
$text.="array(\n";
  
$count=count($array);

   foreach (
$array as $key=>$value)
   {
      
$x++;

       if (
is_array($value))
       {
           if(
substr($text,-1,1)==')')    $text .= ',';
          
$text.=$tab."\t".'"'.$key.'"'." => ".arraytostring($value, $depth+1);
           continue;
       }

      
$text.=$tab."\t"."\"$key\" => \"$value\"";

       if (
$count!=$x) $text.=",\n";
   }

  
$text.="\n".$tab.")\n";

   if(
substr($text, -4, 4)=='),),')$text.='))';

   return
$text;
}
?>
Vladson
14-Mar-2007 04:18
Hope someone find it useful..

<?php
/*
    Function: eratosthenes
    Usage: array eratosthenes ( int max_value )

    Description:
    Sieve of Eratosthenes is a simple, ancient algorithm
    for finding all prime numbers up to a specified integer.
    It was created by Eratosthenes, an ancient Greek mathematician.
*/
function eratosthenes($max) {
   
$sieve = array_fill(2, ($max-1), false);
    while (
$key = array_search(false, $sieve)) {
       
$sieve[$key] = true;
        for (
$i=$key*$key; $i<=$max; $i+=$key) {
            if (
array_key_exists($i, $sieve)) {
                unset(
$sieve[$i]);
            }
        }
    }
    return
array_keys($sieve);
}
?>
piotr dot galas+phpnet at gmail dot com
13-Mar-2007 11:57
Function which converts array to string but not serialize it.

function arraytostring($array)
{
    $text.="array(";
    $count=count($array);

    foreach ($array as $key=>$value)
    {
        $x++;

        if (is_array($value))
        {
            if(substr($text,-1,1)==')')    $text .= ',';
            $text.='"'.$key.'"'."=>".arraytostring($value);
            continue;
        }

        $text.="\"$key\"=>\"$value\"";

        if ($count!=$x) $text.=",";
    }

    $text.=")";

    if(substr($text, -4, 4)=='),),')$text.='))';

    return $text;
}
aflavio at gmail dot com
01-Mar-2007 10:45
/* Correcting me last post */

/**
    * Remove a value from a array
    * @param string $val
    * @param array $arr
    * @return array $array_remval
    */
    function array_remval($val, &$arr)
    {
          $array_remval = $arr;
          for($x=0;$x<count($array_remval);$x++)
          {
              $i=array_search($val,$array_remval);
              if (is_numeric($i)) {
                  $array_temp  = array_slice($array_remval, 0, $i );
                $array_temp2 = array_slice($array_remval, $i+1, count($array_remval)-1 );
                $array_remval = array_merge($array_temp, $array_temp2);
              }
          }
          return $array_remval;
    }

$stack=Array('apple','banana','pear','apple', 'cherry', 'apple');
array_remval("apple", $stack);

//output: Array('banana','pear', 'cherry')
aflavio at gmail dot com
01-Mar-2007 08:29
/**
    * Remove a value from a array
    * @param string $val
    * @param array $arr
    * @return array $array_remval
    */
    function array_remval($val, &$arr)
    {
          $array_remval = $arr;
          for($x=0;$x<count($array_remval)-1;$x++)
          {
              $i=array_search($val,$array_remval);
              if($i===false)return false;
              $array_remval=array_merge(array_slice($array_remval, 0,$i), array_slice($array_remval, $i+1));
          }
          return $array_remval;
    }

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

output $stack = array("orange", "banana", "raspberry");
rune at zedeler dot dk
28-Feb-2007 05:42
Notice that keys are considered equal if they are "=="-equal. That is:

<?
$a
= array();
$a[1] = 'this is the first value';
$a[true] = 'this value overrides the first value';
$a['1'] = 'so does this one';
?>
admin \x40 uostas.net
23-Feb-2007 05:09
simple function to remove element from array
saving index sequence
<?php

function array_remval($val,&$arr){
 
$i=array_search($val,$arr);
  if(
$i===false)return false;
 
$arr=array_merge(array_slice($arr, 0,$i), array_slice($arr, $i+1));
  return
true;
}
?>

example:
<?php
$input
=Array('a','b','c','d','e');
array_remval('d',$input);
//result:
//Array('a','b','c','e');
?>
christian at enovo dot dk
18-Feb-2007 01:03
function array_flatten(&$a,$pref='',$sep='_') {
        $ret=array();
        foreach ($a as $i => $j)
        {
            if (is_array($j)) {
                $ret=array_merge($ret, array_flatten($j, $pref . ( strlen($pref) != 0 ? $sep : '' ) . $i ) );
            }
            else
            {
                $ret[$pref. $sep . $i] = $j;
            }
        }
        return $ret;
    }
Colin
10-Feb-2007 06:31
I couldn't get the previous set pointer functions working for whatever reason so I modifed. I trigger errors if needed but obviously you can do whatever

    // setPointer - Sets the pointer to the provided $key in provided $array
    final private function setPointer(&$array, $set_key) {
   
        // Check if $array is an array
        if (!is_array($array)) {
            trigger_error('$array must be an array', E_USER_ERROR);
            }
   
        // Check if $key is in $array
        if (!array_key_exists($set_key, $array)) {
            trigger_error('$set_key must exist in $array', E_USER_ERROR);
            }

        // Set array pointer to first element
        reset($array);
   
        // Cycle through array
        while ($set_key != key($array)) {
       
            // Advance the pointer
            next($array);
            }
        }

Try with:
$array = array();
$array[0] = 'zero';
$array[1] = 'one';
$array[2] = 'two';
$array[3] = 'three';

// Set the pointer
setPointer($array, 1);

// Display elements
echo current($array); // Outputs 'one'
echo next($array); // Outputs 'two'
hannes dot dahlberg at gmail dot com
06-Feb-2007 02:12
A small function to get the median of an array filled with numbers

function median($array)
{
    sort($array);
    return ($array[ceil((count($array) / 2)) - 1] + $array[floor((count($array) / 2))]) / 2;
}
dkrysiak at o2 dot pl
02-Feb-2007 09:40
// note: my previous post have one small error in call to array_key_exists() - posting again - please remove this comment and that note :-)

<?php
/* Another version of subArr() function by simone dot carletti at unimc dot it: */
//{{{ array_select()
/**
* Choose array element with given keys
*
* @param    Array    $arr
* @param    Array    $keys        Keys/indexes of elements to choose
* @return    Array        Array with elements being references to the elements od original array with chosen indexes.
*/
function &array_select($arr, $keys)
{
   
$res = array();
    foreach (
$keys as $key) {
        if (
array_key_exists($key, $arr)) {
           
$res[$key] =& $arr[$key];
        }
    }
    return
$res;
}
// end: array_select() }}}
/*
In my opinion it should be faster than subArr().

Another difference from subArr() is that elements of returned array are references to the same variables as elements of original array (this can be easily changed)
*/
?>
Mark Lindeman
17-Jan-2007 11:10
Very simple solution for changing the key of an associative array, of course it will fail in a lot of scenarios, but will do the trick in simple arrays:

<?php
function replace_key(&$input, $from_key, $to_key)
{
   
$input = unserialize(str_replace(':"'.$from_key.'";', ':"'.$to_key.'";',serialize($input)));
}

$array =array("a"=>1, "B"=>2, "c"=>3);
replace_key($array, "B", "b");
print_r($array);
?>
Output:
Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)
php_spam {at] erif dot org
28-Dec-2006 07:52
public domain, yadda yadda. :)

This function takes a flatfile-like array (like the results of a joined query) and normalizes it based on whichever parameters you like.

<?php

 
function hashByFields($things,$fields) {
   
$retval=null;
   
$count = count($fields);
    foreach (
$things as $thing) {
     
$fwibble =& $retval;
      for (
$j=0;$j<$count;$j++) {
       
$val = $thing[$fields[$j]];
        if (
$j == $count - 1) {
         
$fwibble[$val] = $thing;
        } else if (!isset(
$fwibble[$val])) {
         
$fwibble[$val] = Array();
        }
       
$fwibble =& $fwibble[$val];
      }
    }
    return
$retval;
  }

?>
filip at mxd dot biz
19-Dec-2006 10:59
a better array_key_set function:

    function array_key_set(&$array, $key=0) {
        if(is_array($array)) {
            if(!array_key_exists($array, $key)) {
                return false;
            }
            reset($array);
            while($current = key($array)) {
                if($current == $key) {
                    return true;
                }
                next($array);
            }
        }
        return false;
    }
simone dot carletti at unimc dot it
28-Nov-2006 04:09
Ever wanted to obtain a subset of an associative array from a list of parameters (stored into a non-associative array)?
Give this a try:

<?php

$params
= array("name" => "Simone", "gender" => "M", "city" => "Macerata", "phone" => 123);
$fields = array("name", "city");

echo
"<pre>";
print_r($params);
print_r($fields);
print_r(subArr($params, $fields));

function
subArr($assocArrHaystack, $arrFields)
{
   
$arrSub = array();

    foreach (
$assocArrHaystack as $key => $value) {
        if (
in_array($key, $arrFields)) {
           
$arrSub[$key] = $value;
        }
    }

    return
$arrSub;
}

?>

And the output is:

Array
(
    [name] => Simone
    [gender] => M
    [city] => Macerata
    [phone] => 123
)
Array
(
    [0] => name
    [1] => city
)
Array
(
    [name] => Simone
    [city] => Macerata
)

Enjoy!

Simone
elkabong at samsalisbury dot co dot uk
13-Nov-2006 12:43
An improvement to the array_deep_copy function I posted ages ago which takes a 'snapshot' of an array, making copies of all actual values referenced... Now it is possible to prevent it traversing the tree forever when an array references itself. You can set the default $maxdepth to anything you like, you should never call this function with the $depth specified!
<?php
/* Make a complete deep copy of an array replacing
references with deep copies until a certain depth is reached
($maxdepth) whereupon references are copied as-is...  */
function array_deep_copy (&$array, &$copy, $maxdepth=50, $depth=0) {
    if(
$depth > $maxdepth) { $copy = $array; return; }
    if(!
is_array($copy)) $copy = array();
    foreach(
$array as $k => &$v) {
        if(
is_array($v)) {        array_deep_copy($v,$copy[$k],$maxdepth,++$depth);
        } else {
           
$copy[$k] = $v;
        }
    }
}

# call it like this:

array_deep_copy($array_to_be_copied,$deep_copy_of_array,$maxdepth);
?>
Hope someone finds it useful!
zspencer at zacharyspencer dot com
01-Nov-2006 03:59
The array system is sadly lacking a "set" function... I needed one that would set the pointer to the key that I specified.

So I wrote my own.

<?
$array
=array();

$array['a']='lala';
$array['b']='blabla';
$array['c']='nono';

set($array, 'b');

echo
current($array);
// outputs blabla

function set(&$array, $key)
{
   
reset($array);
    while(
$current=key($array))
    {
        if(
$current==$key)
        {
            return
true;
        }
       
next($array);
    }
    return
false;
   
}
?>
sneskid at hotmail dot com
24-Oct-2006 03:30
notice
<?php
$v
= array();

$v['0'] = 's';
$v[0] = 'i';
echo
$v['0'];
echo
$v[0];

$v['.1'] = 's';
$v[.1] = 'i';
echo
$v['.1'];
echo
$v[.1];

$v['0.1'] = 's';
$v[0.1] = 'i';
echo
$v['0.1'];
echo
$v[0.1];

// output: iisi

foreach($v as $key => $val) echo $v[$key] . ' : ' . $val . "\r\n";

// output: iisi
?>

This means foreach preserves the key data type, it also means arrays distinguish between float numbers and float like  strings, unlike integers
r2rien at gmail dot com
16-Oct-2006 02:06
Regarding the string to array (parse_array) function posted by Kevin Law(thanks) and urlencoded by vinaur(thanks) ,
The function will not work correctly if you use integer values as keys.
Thus I exchanged array_merge with a simple combined operator.

For example dealing with 4digit year strings as keys; parse_array(2006:abc,B:bcd) will produce

=> with array_merge:
<?php //...
$result = array_merge($result, parse_line2array(substr($line,$comma_pos+1)));
//...
$result = array_merge($result, parse_line2array($line));
//... ?>
Array (
    [0] => abc
    [B] => bcd
)

=> with combined operator:
<?php //...
$result += parse_line2array(substr($line,$comma_pos+1));
//...
$result += parse_line2array($line);
//... ?>
Array
(
    [2006] => abc
    [B] => bcd
)
kthejoker - google mail
20-Sep-2006 07:00
re jeremyquintion:

your solution is array_merge(), which will reindex a numeric array.

So if you have

$array[0] = "something";
$array[1] = "something else";
$array[2] = "yet another";

unset($array[1]);
array_merge($array);

the result is

$array[0] = "something";
$array[1] = "yet another";

and then you can use a for loop accordingly. Obviously this isn't ideal if you want to maintain key association.
jeremyquinton at gmail dot com
31-Aug-2006 12:20
//using the foreach loop of php instead of a normal
//for loop with the sizeof operator after unset is used.

$values = array();

array_push($values,"lion");
array_push($values,"elephant");
array_push($values,"cheetah");
array_push($values,"wildebeest");

unset($values[2]);

//normal for loop thinks array size is three
//when sizoef function is used in conjunction
//the for loop.
for($i = 0;$i < sizeof($values); $i++) {
     echo "animals " . $values[$i]. "\n";
}
//prints
animals lion
animals elephant
animals

echo "\n";
//foreach prints the three values left properly
foreach($values as $animals) {
     echo "animal " . $animals. "\n";
}
//prints
animal lion
animal elephant
animal wildebeest

//simple but valid
ob at babcom dot biz
28-Aug-2006 05:18
Regarding my own posting 2 postings down about the function ArrayDepth() to find the maximum depth of a multidimensional array:

A number of functions for counting array dimensions have been posted. And I tried using them. Yet, if at all they only return the depth of the first branch of the array. They can not handle arrays where a later path holds a more dimension than the first.

My version will check all paths down the array and return the maximum depth. That's why I posted it.
ob at babcom dot biz
28-Aug-2006 02:56
Here are two functions Array2String() and String2Array() based on functions posted below by daenders AT yahoo DOT com.

An improvement handling NULL values correctly was posted by designatevoid at gmail dot com.

My version also solves the NULL-value-problem plus keeps support of multidimensional arrays.

<?php
// convert a multidimensional array to url save and encoded string
// usage: string Array2String( array Array )

function Array2String($Array) {
 
$Return='';
 
$NullValue="^^^";
  foreach (
$Array as $Key => $Value) {
    if(
is_array($Value))
     
$ReturnValue='^^array^'.Array2String($Value);
    else
     
$ReturnValue=(strlen($Value)>0)?$Value:$NullValue;
   
$Return.=urlencode(base64_encode($Key)) . '|' . urlencode(base64_encode($ReturnValue)).'||';
  }
  return
urlencode(substr($Return,0,-2));
}
?>

<?php
// convert a string generated with Array2String() back to the original (multidimensional) array
// usage: array String2Array ( string String)

function String2Array($String) {
 
$Return=array();
 
$String=urldecode($String);
 
$TempArray=explode('||',$String);
 
$NullValue=urlencode(base64_encode("^^^"));
  foreach (
$TempArray as $TempValue) {
    list(
$Key,$Value)=explode('|',$TempValue);
   
$DecodedKey=base64_decode(urldecode($Key));
    if(
$Value!=$NullValue) {
     
$ReturnValue=base64_decode(urldecode($Value));
      if(
substr($ReturnValue,0,8)=='^^array^')
       
$ReturnValue=String2Array(substr($ReturnValue,8));
     
$Return[$DecodedKey]=$ReturnValue;
     }
    else
     
$Return[$DecodedKey]=NULL;
  }
  return
$Return;
}
?>
ob at babcom dot biz
28-Aug-2006 01:23
Here is a function to find out the maximum depth of a multidimensional array.

<?php
// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)

function ArrayDepth($Array,$DepthCount=-1,$DepthArray=array()) {
 
$DepthCount++;
  if (
is_array($Array))
    foreach (
$Array as $Key => $Value)
     
$DepthArray[]=ArrayDepth($Value,$DepthCount);
  else
    return
$DepthCount;
  foreach(
$DepthArray as $Value)
   
$Depth=$Value>$Depth?$Value:$Depth;
  return
$Depth;
}
?>
ob at babcom dot biz
28-Aug-2006 01:18
Regarding the function of spam at madhermit dot net from January 9th 2006:

That function only preserves the deepest keys and values.
If you try to flatten an array with that function where the deepest instance of keys might be the same where as keys in the "key-path" are different, values will be overwritten.

So here is a function that preserves the whole key-path and the keys of the flattened array will be string keys consisting of the key-path separated by $Separator.

<?php
// flatten multidimensional array to one dimension
// preserves keys by generating a key for the flattened array which consists of the
// key-path of the multidimensional array separated by $Separator
// usage: array ArrayFlatten( array Array [, string Separator] )

function ArrayFlatten($Array,$Separator="_",$FlattenedKey='') {
 
$FlattenedArray=Array();
  foreach(
$Array as $Key => $Value) {
    if(
is_Array($Value))
     
$FlattenedArray=Array_merge($FlattenedArray,
                                 
ArrayFlatten($Value,$Separator,
                                               (
strlen($FlattenedKey)>0
                                               
?$FlattenedKey.$Separator
                                               
:"").$Key)
                                               );
    else
     
$FlattenedArray[$FlattenedKey.$Separator.$Key]=$Value;
  }
  return
$FlattenedArray;
}
?>
sergio at {NO_SPAM_PLEASE]inservibile dot org
16-Aug-2006 02:17
In a pratical problem, I was involved in a system of queries giving the behaviour of all combinations of some parameters. How to write those queries?
The problem was to generate automatically every possible combination of those parameters. I didn't find a function and I wrote it.
(Naturally, a different way could be to build a binary sequence, but I find this function more compact and useful).
So, consider an array of objects and suppose to need all possibile combinations of those objects. Here is the function, that could be useful for some folk.
Enjoy.

<?php
function combinations($elements) {
         if (
is_array($elements)) {
           
/*
            I want to generate an array of combinations, i.e. an array whose elements are arrays
            composed by the elements of the starting object, combined in all possible ways.
            The empty array must be an element of the target array.
            */
           
$combinations=array(array()); # don't forget the empty arrangement!
            /*
            Built the target array, the algorithm is to repeat the operations below for each object of the starting array:
            - take the object from the starting array;
            - generate all arrays given by the target array elements merged with the current object;
            - add every new combination to the target array (the array of arrays);
            - add the current object (as a vector) to the target array, as a combination of one element.
            */
           
foreach ($elements as $element) {
                   
$new_combinations=array(); # temporary array, see below
                   
foreach ($combinations as $combination) {
                           
$new_combination=array_merge($combination,(array)$element);
                           
# I cannot merge directly with the main array ($combinations) because I'm in the foreach cycle
                            # I use a temporary array
                           
array_push($new_combinations,$new_combination);
                            }
                   
$combinations=array_merge($combinations,$new_combinations);
                    }
            return
$combinations;
            } else {
            return
false;
            }
         }
?>

To test the function:

<?php
$elements
=array('bitter','sour','salty','sweet');
print_r(combinations($elements));
?>

The exemple was suggested in 6th century BC.
See why on: http://en.wikipedia.org/wiki/Combinatorics#Overview_and_history
Nicolai Bloch
10-Aug-2006 09:51
Here are two functions for checking if an array contains numeric or string indexes only.
Hope someone else will find them useful.

<?php
//Check for numeric array
function isNumeric($ar) {
 
$keys = array_keys($ar);
 
natsort($keys); //String keys will be last
 
return is_int(array_pop($keys));
}

//Check for associative array
function isAssoc($ar) {
 
$keys = array_keys($ar);
 
natsort($keys); //Numeric keys will be first
 
return is_string(array_shift($keys));
}
?>
za at byza dot it
20-Jul-2006 05:52
Updated functions for moving element between associative arrays using a numeric index.

Sample:
$a=array("04"=>"alpha",4=>"bravo","c"=>"charlie","d"=>"delta");
$b=array_move($a,4,2);

Move element "bravo" after "delta" keeping keys.
Old function probably goes wrong moving "alpha": caused by array_search that match numeric index 4 with "04" (string).

Follow:

<?php
// array functions - 20/07/2006 12.28

if(!defined("ARRAY_FUNCS")) {   
   
// Swap 2 elements in array preserving keys.
   
function array_swap(&$array,$key1,$key2) {
       
$v1=$array[$key1];
       
$v2=$array[$key2];
       
$out=array();
        foreach(
$array as $i=>$v) {
            if(
$i===$key1) {
               
$i=$key2;
               
$v=$v2;
            } else if(
$i===$key2) {
               
$i=$key1;
               
$v=$v1;
            }
           
$out[$i]=$v;
        }
        return
$out;
    }
   
   
//  Get a key position in array
   
function array_kpos(&$array,$key) {
       
$x=0;
        foreach(
$array as $i=>$v) {
            if(
$key===$i) return $x;
           
$x++;
        }
        return
false;
    }
   
   
// Return key by position
   
function array_kbypos(&$array,$pos) {
       
$x=0;
        foreach(
$array as $i=>$v) {
            if(
$pos==$x++) return $i;
        }
        return
false;
    }

   
// Move an element inside an array preserving keys
    // $relpos should be like -1, +2...
   
function array_move(&$array,$key,$relpos) {
        if(!
$relpos) return false;
       
$from=array_kpos($array,$key);
        if(
$from===false) return false;
       
$to=$from+$relpos+($relpos>0?1:0);
       
$len=count($array);
        if(
$to>=$len) {
           
$val=$array[$key];
            unset(
$array[$key]);
           
$array[$key]=$val;
        } else {
            if(
$to<0) $to=0;
           
$new=array();       
           
$x=0;
            foreach(
$array as  $i=>$v) {
                if(
$x++==$to) $new[$key]=$array[$key];
                if(
$i!==$key) $new[$i]=$v;
            }
           
$array=$new;
        }
        return
$array;
    }

   
define("ARRAY_FUNCS",true);
}
?>
g8z at yahoo dot com
19-Jul-2006 10:42
<?php
/**
filter_by_occurrence scans an array, and depending on the $exclusive parameter, includes or excludes elements occuring at least $min_occurences times, and at most $max_occurances times.

parameters:

$data_set = the array to work on
$min_occurrences = the minimum number of occurrences
$max_occurrences = the maximum number of occurrences (zero for unlimited)
$exclusive = if true, will return only results that do not occur within the specified bounds

Courtesy of the $5 Script Achive: http://www.tufat.com
**/

function filter_by_occurrence ($data_set, $min_occurrences, $max_occurrences = 0, $exclusive = false) {
   
$results = array();

   
// iterate through unique elements
   
foreach (array_unique($data_set) as $value) {

       
// count how many times element is in the array
       
$count = 0;
        foreach (
$data_set as $element) {
            if (
$element == $value)
               
$count++;
        }

       
// check if meets min_occurences
       
$is_in_range = false;

        if (
$count >= $min_occurrences) {
           
// check if meets max_occurrences (unless max_occurences is 0)
           
if ( $count <= $max_occurrences || $max_occurrences == 0)
               
$is_in_range = true;
        }

       
// add item to array if appropriate
       
if ($is_in_range && !$exclusive)
           
array_push($results, $value);
        if (!
$is_in_range && $exclusive)
           
array_push($results, $value);
    }

   
// return results
   
return $results;
}

// EXAMPLE:

$test_data = array('pizza', 'ham', 'pizza', 'pizza', 'ham', 'fish', 'fish', 'fish', 'fish', 'dinosaur');

foreach (
filter_by_occurrence( $test_data, 3, 0, false ) as $value)
{
    print
$value . ' occurs at least 3 times. <br />';
}

?>
nick
11-Jul-2006 02:46
This little function will move an array element up or down. Unlike the similar function in a previous comment this will work for associative arrays too.

Because it uses current to traverse the array it will fail if a value is false (or 0). It could probably be rewritten to use each() but I couldn't work it out.
<?php
function array_move_element($array, $value, $direction = 'up') {
   
   
$temp = array();
   
    if(
end($array) == $value && $direction == 'down') {
        return
$array;
    }
    if(
reset($array) == $value && $direction == 'up') {
        return
$array;
    }

    while (
$array_value = current($array)) {
       
       
$this_key = key($array);

        if (
$array_value == $value) {
            if(
$direction == 'down') {
               
$next_value = next($array);
               
$temp[key($array)] = $next_value;
               
$temp[$this_key] = $array_value;
            } else {
               
$prev_value = prev($array);
               
$prev_key = key($array);
                unset(
$temp[$prev_key]);
               
$temp[$this_key] = $array_value;
               
$temp[$prev_key] = $prev_value;
               
next($array);
               
next($array);
            }
            continue;
        } else {
           
$temp[$this_key] = $array_value;
        }

       
next($array);
    }
    return
$temp;
   
}
?>
kroczu at interia dot pl
06-Jul-2006 03:53
<?
//A little function to convert array to simle xml:

function array_xml($array, $num_prefix = "num_")
{
    if(!
is_array($array)) // text
   
{
        return
$array;
    }
    else
    {
        foreach(
$array as $key=>$val) // subnode
       
{
           
$key = (is_numeric($key)? $num_prefix.$key : $key);
           
$return.="<".$key.">".array_xml($val, $num_prefix)."</".$key.">";
        }
    }

    return
$return;
}

//example:

$array[0][0]                    = 1;
$array[0]['test']               = "test";
$array['test1']['test2']        = "test";
$array['test'][0]               = "test";
$array['test'][1]['test_x']     = $array;

print_r($array);

print
"<xml>";

print
array_xml($array);

print
"</xml>";

/*

print_r($array) previev:

Array
(
    [0] => Array
        (
            [0] => 1
            [test] => test
        )
    [test1] => Array
        (
            [test2] => test
        )
    [test] => Array
        (
            [0] => test
            [1] => Array
                (
                    [test_x] => Array
                        (
                            [0] => Array
                                (
                                    [0] => 1
                                    [test] => test
                                )
                            [test1] => Array
                                (
                                    [test2] => test
                                )
                            [test] => Array
                                (
                                    [0] => test
                                )
                        )
                )
        )
)

result xml in firefox preview:

-<xml>
    -     <num_0>
            <num_0>1</num_0>
            <test>test</test>
        </num_0>
    -    <test1>
            <test2>test</test2>
        </test1>
    -    <test>
            <num_0>test</num_0>
        -    <num_1>
            -    <test_x>
                -    <num_0>
                        <num_0>1</num_0>
                        <test>test</test>
                    </num_0>
                -    <test1>
                        <test2>test</test2>
                    </test1>
                -    <test>
                        <num_0>test</num_0>
                    </test>
                </test_x>
            </num_1>
        </test>
 </xml>

*/
?>
vinaur at gmail dot com
06-Jun-2006 10:36
Regarding the array to string (parse_line) and string to array (parse_array) functions posted below by Kevin Law.

The functions will not work correctly if the array being parsed contains values that include commas and possibly parentheses.

To solve this problem I added urlencode and urldecode functions and the result looks like this:

<?php
function parse_line($array){
   
$line = "";
    foreach(
$array AS $key => $value){
        if(
is_array($value)){
           
$value = "(". parse_line($value) . ")";
        }
        else
        {
           
$value = urlencode($value);
        }
       
$line = $line . "," . urlencode($key) . ":" . $value . "";           
    }
   
$line = substr($line, 1);
    return
$line;
}

function
parse_array($line){
  
$q_pos = strpos($line, ":");
  
$name = urldecode(substr($line,0,$q_pos));
  
$line = trim(substr($line,$q_pos+1));
  
$open_backet_pos = strpos($line, "(");

   if(
$open_backet_pos===false || $open_backet_pos>0){
      
$comma_pos = strpos($line, ",");
       if(
$comma_pos===false){
          
$result[$name] = urldecode($line);
          
$line = "";
       }else{
          
$result[$name] = urldecode(substr($line,0,$comma_pos));
          
$result = array_merge($result, parse_array(substr($line,$comma_pos+1)));
          
$line = "";
       }
   }else if (
$open_backet_pos==0){
      
$line = substr($line,1);
      
$num_backet = 1;
      
$line_char_array = str_split($line);
       for(
$index = 0; count($line_char_array); $index++){
           if(
$line_char_array[$index] == '('){
              
$num_backet++;
           }else if (
$line_char_array[$index] == ')'){
              
$num_backet--;
           }
           if(
$num_backet == 0){
               break;
           }
       }
      
$sub_line = substr($line,0,$index);
      
$result[$name] = parse_array($sub_line);
      
$line = substr($line,$index+2);
   }
   if(
strlen($line)!=0){
      
$result = array_merge($result, parse_array($line));
   }

   return
$result;
}
?>
php_spam at erif dot org
27-May-2006 09:15
Public domain, yadda yadda.  This is an extension of the assocSort below, patched up a bit.  Feedback would be wonderful.

<?php

 
function assocMultiSort(&$array,$keys,$directions=true) {
    if (!
is_array($array) || count($array) == 0) return true;
    if (!
is_array($keys)) { $keys = Array($keys); }

   
//we want "current" instead of necessarily the "zeroth" element; there may not be a zeroth element
   
$test = current($array);

   
$assocSortCompare = '';

    for (
$i=0,$count=count($keys);$i<$count;$i++) {
     
$key = $keys[$i];
      if (
is_array($directions)) {
       
$direction = $directions[$i];
      } else {
       
$direction = $directions;
      }
      if (
$i > 0) $assocSortCompare .= 'if ($retval != 0) return $retval; ';
     
$assocSortCompare .= '$ax = $a["'.$key.'"]; $bx = $b["'.$key.'"];';

     
//TODO -- if it's "blank", search up the list until we find something not blank
     
if (is_numeric($test[$key]) || ($test[$key] == ((int)$test[$key]))) {
        if (
$direction) {
         
$assocSortCompare.= ' $retval = ($ax == $bx) ? 0 : (($ax < $bx) ? -1 : 1);';
        } else {
         
$assocSortCompare.= ' $retval = ($ax == $bx) ? 0 : (($ax < $bx) ? 1 : -1);';
        }
      } else {
        if (
$direction) {
         
$assocSortCompare.= ' $retval = strcmp($ax,$bx);';
        } else {
         
$assocSortCompare.= ' $retval = strcmp($bx,$ax);';
        }
      }
    }

   
$assocSortCompare.= ' return $retval;';
   
$assocSortCompare = create_function('$a,$b',$assocSortCompare);
   
$retval = usort($array,$assocSortCompare);
    return
$retval;
  }

?>
ben
13-Apr-2006 11:59
In reference to the cleanArray function below, note that it checks the value using the empty() function and removes it. This will also remove the integer value 0 and the string "0" among other possibly unexpected things. Check the manual entry for empty().
g dot bell at NOSPAM dot managesys dot com dot au
03-Apr-2006 12:57
/*
function to give array of ranks. Handles ties.
input     $arr is zero based array to be ranked
        $order is the sorting order
            'asc' (default) ranks smallest as 1
            'desc' ranks largest as 1
output    zero based array of ranks.
Ties (repeated values) given equal (integer) values
*/
function array_rank($arr,$order='asc') {
    // $direction parameter
    foreach($arr as $being_ranked) {
        $t1 = $t2 = 0;
        if ($order == 'asc') {
            foreach ($arr as $checking) {
                if ($checking > $being_ranked) continue;
                if ($checking < $being_ranked) {
                    $t1++;
                } else {
                    $t2++; // equal so increment tie counter
                }
            }
        } elseif ($order == 'desc') {
            foreach ($arr as $checking) {
                if ($checking < $being_ranked) continue;
                if ($checking > $being_ranked) {
                    $t1++;
                } else {
                    $t2++; // equal so increment tie counter
                }
            }
        }
        $ranks[] = floor($t1 + ($t2 + 1) / 2);
    }
    return $ranks;
}
administrador(ensaimada)sphoera(punt)com
31-Mar-2006 02:37
With this simple function you can convert a (partial) bidimensional array into a XHTML table structure:
<?php

$table
= array();
$table[1][1] = "first";
$table[2][1] = "second";
$table[5][3] = "odd one";
$table[1][2] = "third";

echo
matrix2table($table);

function
matrix2table($arr,$tbattrs = "width='100%' border='1'", $clattrs="align='center'"){
   
$maxX = $maxY = 1;
    for (
$x=0;$x<100;$x++){
        for (
$y=0;$y<100;$y++){
            if (
$arr[$x][$y]!=""){
                if (
$maxX < $x) $maxX = $x;
                if (
$maxY < $y) $maxY = $y;
            }
        }
    }
   
$retval = "<table $tbattrs>\n";
    for (
$x=1;$x<=$maxX;$x++){
       
$retval.=" <tr>\n";
        for (
$y=1;$y<=$maxY;$y++){
           
$retval.= (isset($arr[$x][$y]))
            ?
"  <td $clattrs>".$arr[$x][$y]."</td>\n"
           
:"  <td $clattrs>&nbsp;</td>\n";
        }
       
$retval.=" </tr>\n";
    }   
    return
$retval."</table>\n";
}

?>
more scripts at http://www.sphoera.com
elkabong at samsalisbury dot co dot uk
24-Mar-2006 11:31
Hello all! I've just been working on a system to automatically manage virtualhosts on an Apache box and I needed to duplicate some multidimensional arrays containing references to other multidimensional array some of which also contained references. These big arrays are defaults which need to be overwritten on a per-virtualhost basis, so copying references into the virtualhost arrays was not an option (as the defults would get corrupted).

After hours of banging me head on the wall, this is what I've come up with:
<?PHP # Tested on PHP Version 5.0.4
# Recursively set $copy[$x] to the actual values of $array[$x]
function array_deep_copy (&$array, &$copy) {
    if(!
is_array($copy)) $copy = array();
    foreach(
$array as $k => $v) {
        if(
is_array($v)) {
           
array_deep_copy($v,$copy[$k]);
        } else {
           
$copy[$k] = $v;
        }
    }
}
# To call it do this:
$my_lovely_reference_free_array = array();
array_deep_copy($my_array_full_of_references, $my_lovely_reference_free_array);
# Now you can modify all of $my_lovely_reference_free_array without
# worrying about $my_array_full_of_references!
?>
NOTE: Don't use this on self-referencing arrays! I haven't tried it yet but I'm guessing an infinate loop will occur...

I hope someone finds this useful, I'm only a beginner so if there's any fatal flaws or improvements please let me know!
alessandronunes at gmail dot com
18-Mar-2006 11:06
The Ninmja sugestion plus multidiomensional array search (recursive):

function cleanArray($array) {
   foreach ($array as $index => $value) {
        if(is_array($array[$index])) $array[$index] = cleanArray($array[$index]);
        if (empty($value)) unset($array[$index]);
   }
   return $array;
}
padraig at NOSPAM dot ohannelly dot com
14-Mar-2006 06:08
Re removing blank elements from arrays, this is even more concise:

<?php

$arraytest
= array_diff($arraytest, array(""));

?>
Nimja
23-Feb-2006 04:35
A very clean and efficient function to remove empty values from an Array.

<?php
function cleanArray($array) {
    foreach (
$array as $index => $value) {
        if (empty(
$value)) unset($array[$index]);
    }
    return
$array;
}
?>
eddypearson at gmail dot com
05-Feb-2006 09:40
Little function to remove blank values from an array (will not reorder indexes however):

function CleanA($arr) {
while ($count < count($arr)) {
if ($arr[$count] == "") {
unset($arr[$count]);
}
$count++;
}
return $arr;
}
Sebastian
31-Jan-2006 11:58
xxellisxx at gmail dot com:

see implode(), it does exactly what you want, but quicker.

$array = array();
$string = implode( '', $array );
xxellisxx at gmail dot com
19-Jan-2006 06:03
Super simple way of converting an array to a string.
function array_to_string($array)
 {
  foreach ($array as $index => $val)
   {
    $val2 .=$val;
   }
  return $val2;
}
spam at madhermit dot net
10-Jan-2006 02:26
Here is a function that recursively flattens an multidimensional array while maintaining keys. Hopefully it is useful to someone..

Example Input:

Array
(
    [name] => John Doe
    [email] => johndoe@earthlink.net
    [addresses] => Array
        (
            [1] => Array
                (
                    [address] => 555 Somewhere
                    [city] => Podunk
                    [state] => CA
                    [zip] => 90120
                )

            [2] => Array
                (
                    [address] => 333 Someother Place
                    [city] => Podunk
                    [state] => CA
                    [zip] => 91103
                )

        )

)
Example output:
Array
(
    [name] => John Doe
    [email] => johndoe@earthlink.net
    [address1] => 555 Somewhere
    [city1] => Podunk
    [state1] => CA
    [zip1] => 90120
    [address2] => 333 Someother Place
    [city2] => Podunk
    [state2] => CA
    [zip2] => 91103
)

<?
function flattenArray($array,$keyname='')
{
   
$tmp = array();
    foreach(
$array as $key => $value)
    {
        if(
is_array($value))
           
$tmp = array_merge($tmp,flattenArray($value,$key));
        else
           
$tmp[$key.$keyname] = $value;
    }
    return
$tmp;
}
?>
Atomo64
04-Jan-2006 02:14
Here's a simple way to convert an array to a string and vice-versa.
Note that it does NOT support string keys,
for more information take a look at what it does:

<?php
class OptionAsArray
{
    function
make_the_arr($value)
    {
       
$newValue=array();
       
$vals=explode('&',$value);
        foreach(
$vals as $v)
        {
            if(
$v{0}=='@')
           
$newValue[]=$this->make_the_arr(
           
urldecode(substr($v,1)));
            else
           
$newValue[]=urldecode($v);
        }
        if(empty(
$newValue))
        return
false;
        else
        return
$newValue;
    }
    function
make_the_value($arr)
    {
       
$newValue=array();
        foreach(
$arr as $value)
        {
            if(
is_array($value))
           
$newValue[]='@'.urlencode(
           
implode('&',$this->make_the_value($value)));
            else
           
$newValue[]=urlencode($value);
        }
        if(empty(
$newValue))
        return
false;
        else
        return
$newValue;
    }
}
?>
ryan1_00 at hotmail dot com
01-Jan-2006 05:02
The following will take a query result and create a dynamic table for it. Using the Key() function to get the table headers and the current() function for the actual values.

$result = mysql_query($qry) or die ("<center> ERROR: ".mysql_error()."</center>");
         
          $x = 0;

          echo "<table border=\"1\" align=\"center\">";     
          while($row = mysql_fetch_assoc($result))
        {
            if ($x == 0) // so that table headers are only created on the first pass
            {
                $col = (count($row)); // counts number of elements in the array
                  $x=1;
                echo "<tr>";
                for ($y=0; $y<$col; $y++)
                {
                    echo "<th>";
                    echo key($row); // gets the names of the fields
                    echo "</th>";
                    next($row);
                }
                echo "</tr>";
            }
            reset($row);
            echo "<tr>";
            for ($y=0; $y<$col; $y++)
            {
                echo "<td valign=\"top\" align=\"left\">";
                echo current($row);
                echo"</td>";
                next($row);
            }
            echo "</tr>";
        }  // end of while loop
jonathan at sharpmedia dot net
05-Dec-2005 03:37
/**
 * Flattens a multimentional array.
 *
 * Takes a multi-dimentional array as input and returns a flattened
 * array as output. Implemented using a non-recursive algorithm.
 * Example:
 * <code>
 * $in = array('John', 'Jim', array('Jane', 'Jasmine'), 'Jake');
 * $out = array_flatten($in);
 * // $out = array('John', 'Jim', 'Jane', 'Jasmine', 'Jake');
 * </code>
 *
 * @author        Jonathan Sharp <jonathan@sharpmedia.net>
 * @var            array
 * @returns        array
 */
function array_flatten($array)
{
    while (($v = array_shift($array)) !== null) {
        if (is_array($v)) {
            $array = array_merge($v, $array);
        } else {
            $tmp[] = $v;
        }
    }
   
    return $tmp;
}
madness AT l33t DOT it
24-Nov-2005 06:18
A little function I like to use instead of the classic one, it lets me choose a better format an is overall more versatile:

<?
function get_image_size($filename, &$imageinfo){
   
$rawdata=getimagesize($filename, $imageinfo);
   
$refineddata=$rawdata;
    if (
$rawdata){
       
$refineddata=$rawdata;
       
$refineddata['width']=$rawdata[0];
       
$refineddata['height']=$rawdata[1];
       
$refineddata['type']=$rawdata[2];
       
$refineddata['attribute']=" ".$rawdata[3];
       
$refineddata[4]=$rawdata['mime'];
    }
    return
$refineddata;
}
?>

Notice I also added the extra space in the attribute field, becuase I usually use it like this:

<?
echo "<img src=\\"foo.jpg"".$imgdata[attribute]." alt=\\"foo" />";
?>

This way if the attribute happens to be a null or empty value the tag doesn't contain double spaces.
stalker at ruun dot de
20-Nov-2005 10:15
I had some problems while selecting sub-arrays from multi-dimensional arrays (like the SQL-WHERE clause), so i wrote the following function:

<?php
function selectMultiArray($__multiarray,$__key,$__value) {
  foreach(
$__multiarray as $multipart) {
    if(
$multipart[$__key] == $__value) {
     
$__return[] = $multipart;
    }
  }
  if(empty(
$__return)) {
    return
FALSE;
  }
  return
$__return;
}
?>

hope someones finding this helpful. If you have better was for getting to this, please answer.

greets,
St4Lk3R
Rajaratnam Thavakumar--thava16 at gmail dot com
25-Oct-2005 05:16
<?php
/*
This will return the N possible future dates acording to your selections of parameters
mydates_array([Which Week in a Month],[Which Day in a Week],[No of Dates have to return])
Eg:- Every 2nd Sunday mydates_array(2,0,10)
$Dateid---> Sunday        - 0 ,     Monday        - 1 ,    Tuesday        - 2,    Wednesday    - 3,   
            Thursday    - 4 ,    Friday        - 5 ,    Saturday    - 6
$weekid---> * can not be greater than 6
            * if weekID is equal 6 it will return the Last Day of the weeek.
            * Eg:-mydates_array(6,1,10);
            * it will Returns 10 Last Mondays
            * Please note weekid 5 is not availble in all months.mydates_array will not returns $no_returns that you want.
            * Eg:-mydates_array(5,1,10);
            * it will Returns 5th Monday
$no_returns--> No of dates that you want
By: Rajaratnam Thavakumar(thava16@hotmail.com)           
*/
function mydates_array($weekid,$Dateid,$no_returns){
  if(
$weekid<=6){
   
$todayweek = date("D");
   
$myarr=array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
    for(
$k=0;$k<=6;$k++){
        if (
$todayweek==$myarr[$k]){
            if(
$k==0){   
               
$currentdate=0;
            }else{
               
$currentdate=$k;
            }
      }
    }
    
//get Dateid ----------------
   
if($Dateid==0){
       
$Newmyday=date("d")-$currentdate;
    }else if (
$Dateid==1){
       
$Newmyday=date("d")-($currentdate-1);
    }else if (
$Dateid==2){
       
$Newmyday=date("d")-($currentdate-2);
    }else if (
$Dateid==3){
       
$Newmyday=date("d")-($currentdate-3);
    }else if (
$Dateid==4){
       
$Newmyday=date("d")-($currentdate-4);
    }else if (
$Dateid==5){
       
$Newmyday=date("d")-($currentdate-5);
    }else if (
$Dateid==6){
       
$Newmyday=date("d")-($currentdate-6);
    }
   
$thisweekId=$weekid;
   
$count=0;
   
$column=0;
   
$myval=$no_returns*5;
    for(
$i=1; $i<=$myval; $i++){
       
$week1a = mktime(0, 0, 0date("m"), $Newmydaydate("Y"));
       
$week123=strftime("%Y-%m-%d", $week1a);
       
$Newmyday=$Newmyday+7;
        list (
$iyear, $imonth, $idate) = split ('[-.-]', $week123); 
          
//Insert Dates into Array
             
if( $idate<10){
             
$idate=trim(str_replace('0','',$idate));
              }
           
$myweekno=ceil(($idate + date("w",mktime(0,0,0,$imonth,0,$iyear)))/7);
             
$row=$myweekno-1;
                  
$Mymonth[$i]=$imonth;
                   if (
$i>1){
                    if (
$Mymonth[$i-1]!=$Mymonth[$i]){
                     
$column=$column+1;
                    }
                    }
                   
$EveDates[$row][$column]=$week123;
     }
   
$count=0;
    for (
$column = 0; $column < $no_returns; $column++ ){  //--for1-----
   
$mynewcount=0
        for(
$row = 0; $row < 6; $row++){ //--for2-----
           
if($EveDates[$row][$column]!="" && $thisweekId!=6){
               list (
$iyear1, $imonth1, $idate1) = split ('[-.-]', $EveDates[$row][$column]);
              
$myweekno=ceil(($idate1 + date("w",mktime(0,0,0,$imonth1,0,$iyear1)))/7);
                    if(
$myweekno==$thisweekId+1){
                           
$week_n1= mktime(0, 0, 0, date("m"), date("d"),  date("Y"));
                           
$week_m1=strftime("%Y-%m-%d", $week_n1);
                            if(
$count < $no_returns && $EveDates[$row][$column] >= $week_m1){
                              
$mydates_array[$count]=$EveDates[$row][$column];
                            }
                       
$count=$count+1;
                }
            }
            else{
             
$mycount=0;
              if (
$row==5 && $thisweekId==6){
                  for(
$e=5; $e>=0; $e--){
                   if(
$EveDates[$e][$column]!=""){
                   break;
                   }
                  }
                   
$week_n1= mktime(0, 0, 0, date("m"), date("d"),  date("Y"));
                   
$week_m1=strftime("%Y-%m-%d", $week_n1);
                    if(
$mycount<$no_returns && $EveDates[$e][$column] >= $week_m1){
                       
$mydates_array[$count]=$EveDates[$e][$column];
                    }
                   
$mycount=$mycount+1;
                   
$count=$count+1
              }
            }
        } 
//--End of for2-----
   
} //--End of for1-----
 
return $mydates_array;
}else{
echo(
'WeekID Cant be  more than six!');
}}
?>
<select name="eventDate" style="border:1 solid #000066" >
<?    // Return 10 Every 2nd Monday dates
$myarray=mydates_array(6,5,10);
 for (
$i=0;$i<count($myarray);$i++){
    list (
$iyear, $imonth, $idate) = split ('[-.-]', $myarray[$i]);
   
$week1a = mktime(0, 0, 0,$imonth, $idate$iyear);
   
$week= strftime("%A %d %B %Y", $week1a);
?>
<option  value="<?=$myarray[$i]?>"><?=$week?></option>
<? }?>
</select>
msajko at gmail dot com
19-Oct-2005 10:25
array_to_string and sister function string_to_array with multi dimensional array support.

// Converts an array to a string that is safe to pass via a URL
function array_to_string($array) {
   $retval = '';
   $null_value = "^^^";
   foreach ($array as $index => $val) {
       if(gettype($val)=='array') $value='^^array^'.array_to_string($val);    else $value=$val;
       if (!$value)
           $value = $null_value;
       $retval .= urlencode(base64_encode($index)) . '|' . urlencode(base64_encode($value)) . '||';
   }
   return urlencode(substr($retval, 0, -2));
}
 
// Converts a string created by array_to_string() back into an array.
function string_to_array($string) {
   $retval = array();
   $string = urldecode($string);
   $tmp_array = explode('||', $string);
   $null_value = urlencode(base64_encode("^^^"));
   foreach ($tmp_array as $tmp_val) {
       list($index, $value) = explode('|', $tmp_val);
       $decoded_index = base64_decode(urldecode($index));
       if($value != $null_value){
           $val= base64_decode(urldecode($value));
           if(substr($val,0,8)=='^^array^') $val=string_to_array(substr($val,8));
           $retval[$decoded_index]=$val;
          }
       else
           $retval[$decoded_index] = NULL;
   }
   return $retval;
}
phpnet_spam at erif dot org
18-Oct-2005 03:36
Thought this might save someone a few hours. :)  Feedback welcome, of course!  Public domain, yadda yadda.

function assocSort(&$array,$key) {
    if (!is_array($array) || count($array) == 0) return true;
    $assocSortCompare  = '$a = $a["'.$key.'"]; $b = $b["'.$key.'"];';

    if (is_numeric($array[0][$key])) {
      $assocSortCompare.= ' return ($a == $b) ? 0 : (($a < $b) ? -1 : 1);';
    } else {
      $assocSortCompare.= ' return strcmp($a,$b);';
    }

    $assocSortCompare = create_function('$a,$b',$assocSortCompare);
    return usort($array,$assocSortCompare);
}
designatevoid at gmail dot com
14-Oct-2005 03:40
Here's an improvement to the array_to_string and string_to_array functions posted by daenders AT yahoo DOT com above.

They now handle NULL values correctly.

<?php

// Converts an array to a string that is safe to pass via a URL
function array_to_string($array) {
   
$retval = '';
   
$null_value = "^^^";
    foreach (
$array as $index => $value) {
        if (!
$value)
           
$value = $null_value;
       
$retval .= urlencode(base64_encode($index)) . '|' . urlencode(base64_encode($value)) . '||';
    }
    return
urlencode(substr($retval, 0, -2));
}
 
// Converts a string created by array_to_string() back into an array.
function string_to_array($string) {
   
$retval = array();
   
$string = urldecode($string);
   
$tmp_array = explode('||', $string);
   
$null_value = urlencode(base64_encode("^^^"));
    foreach (
$tmp_array as $tmp_val) {
        list(
$index, $value) = explode('|', $tmp_val);
       
$decoded_index = base64_decode(urldecode($index));
        if(
$value != $null_value)
           
$retval[$decoded_index] = base64_decode(urldecode($value));
        else
           
$retval[$decoded_index] = NULL;
    }
    return
$retval;
}

?>
aidan at php dot net
09-Oct-2005 10:32
To convert an array to a HTML table, see:
http://aidanlister.com/repos/v/function.array2table.php

PEAR also provides a simular package with many more features,
http://pear.php.net/package/Var_Dump
za at lombardiacom dot it
27-Sep-2005 05:01
<?php
   
// Swap 2 elements in array preserving keys.
   
function array_swap(&$array,$key1,$key2) {
       
$v1=$array[$key1];
       
$v2=$array[$key2];
       
$out=array();
        foreach(
$array as $i=>$v) {
            if(
$i==$key1) {
               
$i=$key2;
               
$v=$v2;
            } else if(
$i==$key2) {
               
$i=$key1;
               
$v=$v1;
            }
           
$out[$i]=$v;
        }
        return
$out;
    }

   
// Move an element inside an array preserving keys.
   
function array_move(&$array,$key,$position) {
       
$from=array_search($key,array_keys($array));
       
$to=$from+$position;   
       
$tot=count($array);
        if(
$position>0) $to++;
        if(
$to<0) $to=0;
        else if(
$to>=$tot) $to=$tot-1;
       
$n=0;
       
$out=array();
        foreach(
$array as $i=>$v) {
            if(
$n==$to) $out[$key]=$array[$key];
            if(
$n++==$from) continue;
           
$out[$i]=$v;
        }       
        return
$out;
    }
?>
Domenic Denicola
15-Aug-2005 08:49
Another JavaScript conversion, this time to objects instead of arrays. They can be accessed the same way, but are declared much shorter, so it saves some download time for your users:

<?
function PhpArrayToJsObject($array, $objName)
{
    return
'var ' . $objName . ' = ' . PhpArrayToJsObject_Recurse($array) . ";\n";
}

function
PhpArrayToJsObject_Recurse($array)
{
   
// Base case of recursion: when the passed value is not a PHP array, just output it (in quotes).
   
if(! is_array($array) )
    {
       
// Handle null specially: otherwise it becomes "".
       
if ($array === null)
        {
            return
'null';
        }
       
        return
'"' . $array . '"';
    }
   
   
// Open this JS object.
   
$retVal = "{";

   
// Output all key/value pairs as "$key" : $value
    // * Output a JS object (using recursion), if $value is a PHP array.
    // * Output the value in quotes, if $value is not an array (see above).
   
$first = true;
    foreach(
$array as $key => $value)
    {
       
// Add a comma before all but the first pair.
       
if (! $first )
        {
           
$retVal .= ', ';
        }
       
$first = false;
       
       
// Quote $key if it's a string.
       
if (is_string($key) )
        {
           
$key = '"' . $key . '"';
        }
       
       
$retVal .= $key . ' : ' . PhpArrayToJsObject_Recurse($value);
    }

   
// Close and return the JS object.
   
return $retVal . "}";
}
?>

Difference from previous function: null values are no longer "" in the object, they are JavaScript null.

So for example:

<?
$theArray
= array("A" => array("a", "b", "c" => array("x")), "B" => "y");
echo
PhpArrayToJsObject($theArray, "myArray");
?>

Gives:

var myArray = {"A" : {0 : "a", 1 : "b", "c" : {0 : "x"}}, "B" : "y"};

You can still access them just like arrays, with myArray["A"][0] or myArray["A"]["c"][0] or whatever. Just shrinks your pages.
dieter peeters
11-Aug-2005 01:35
in response to: Domenic Denicola

I reworked your function a bit and thought i just as well could post it.

Below is the cleaner version, just cut and paste ;) The third parameter is of little use to the coder, unless javascript declaration of variables changes at some point in the future - who knows.

Only minor point is the added parameter which probably gets copied every recursive call with an empty value, though i don't know the exact ways how php handles recursion internally. Most of the time php is pretty smart when optimizing code and an empty string shouldn't take much memory anyway :)

<?php
function phpArrayToJsArray($name,$array,$prePend='var ')
{
    if (
is_array($array)) { // Array recursion
       
$result = $name.' = new Array();'."\n";
        foreach (
$array as $key => $value) {
          
$result .= phpArrayToJsArray($name.'["'.$key.'"]',$value,'');
        }
    } else { 
// Base case of recursion
       
$result = $name.' = "'.$array.'";'."\n";
    }
    return
$prePend.$result;
}
?>
michael at imreo com
21-Jul-2005 02:20
Reply to array_cartesian_product of skopek at mediatac dot com, 13-Oct-2004 12:44:

Your function does not work in my configuration (WinXP, apache 2.0, php 4.3.11).
This part of code:
...
} else { //if next returns false, then reset and go on with previuos array...
  reset($arrays[$j]);
}
...
cause infinite loop.
Replacing to
...
} elseif (isset($arrays[$j])) {
  reset($arrays[$j]);
}
...
works good.

My complete working function (additionaly strings as keys are allowed):
<?php
function array_cartesian_product($arrays)
{
   
$result = array();
   
$arrays = array_values($arrays);
   
$sizeIn = sizeof($arrays);
   
$size = $sizeIn > 0 ? 1 : 0;
    foreach (
$arrays as $array)
       
$size = $size * sizeof($array);
    for (
$i = 0; $i < $size; $i ++)
    {
       
$result[$i] = array();
        for (
$j = 0; $j < $sizeIn; $j ++)
           
array_push($result[$i], current($arrays[$j]));
        for (
$j = ($sizeIn -1); $j >= 0; $j --)
        {
            if (
next($arrays[$j]))
                break;
            elseif (isset (
$arrays[$j]))
               
reset($arrays[$j]);
        }
    }
    return
$result;
}
?>
daenders AT yahoo DOT com
08-Jul-2005 10:49
Several people here have posted functions for converting arrays to strings, but nobody posted a sister function that would convert it back.  Also, their data is not URL safe.  These functions are URL safe, hide the data by MIME encoding it, and are much shorter.  Enjoy.  :-)

<?php

// Converts an array to a string that is safe to pass via a URL
function array_to_string($array) {
   
$retval = '';
    foreach (
$array as $index => $value) {
       
$retval .= urlencode(base64_encode($index)) . '|' . urlencode(base64_encode($value)) . '||';
    }
    return
urlencode(substr($retval, 0, -2));
}
   
// Converts a string created by array_to_string() back into an array.
function string_to_array($string) {
   
$retval = array();
   
$string = urldecode($string);
   
$tmp_array = explode('||', $string);
    foreach (
$tmp_array as $tmp_val) {
        list(
$index, $value) = explode('|', $tmp_val);
       
$retval[base64_decode(urldecode($index))] = base64_decode(urldecode($value));
    }  
    return
$retval;
}

// Example:
$array1 = array('index1' => 'val1', 'index2' => 'val2', 'index3' => 'val3');
echo
'<pre>'; print_r($array1); echo '</pre>';
$string = array_to_string($array1);
echo
'$string: '.$string.'<br />';
$array2 = string_to_array($string);
echo
'<pre>'; print_r($array2); echo '</pre>';

?>
casey geene
30-Apr-2005 12:14
Handy function to walk through an array to get an offset with a given path.

<?php
function &array_path(&$array, $path) {
    if(!
is_array($array)) {
       
trigger_error('array_path(): First argument should be an array', E_USER_WARNING);
    }
   
settype($path, 'array');
   
   
$offset =& $array;
    foreach (
$path as $index) {
        if (!isset(
$offset[$index])) {
           
trigger_error("Undefined offset: $index");
            return
false;
        }
       
$offset =& $offset[$index];
    }
   
    return
$offset;
}

$a = array(
        
1 => array(
                 
2 => array(
                          
3 => 'hi'
                      
)
              )
     );
    
echo
array_path($a, array(1, 2, 3));

$ref =& array_path($a, array(1, 2));

$ref = array('hello');
?>
garis at intec dot edu dot do
29-Apr-2005 05:55
this array are always used on form querys... is a nice way to simplify the date inputs

<?php
$dia
= array('', 'Lunes','Martes','Miercoles','Jueves','Viernes','Sabado', 'Domingo');
$mes = array('', 'Enero','Febrero','Marzo','Abril','Mayo','Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre');
?>

and you call monday like $dia['1']...

i used it on a form, that have a lot of date inputs, cuz i wanted to minimize the size of my file..
admin at snibworks dot com
20-Apr-2005 05:40
I have made a new array function called array_split.

It's like explode() for arrays. It searches the array for a specific value and splits the array into chunks divided by that value.

<?php
function array_split($key, $array)
{
    if(!
is_array($array))trigger_error("Invalid type provided for
second parameter of array_split"
,E_USER_ERROR);
   
$rarray = array();
   
$curkey = 0;
    foreach(
$array as $value)
    {
        if(
$value == $key)
        {
           
$curkey++;
            continue;
        }
       
$rarray[$curkey][] = $value;
    }
    return
$rarray;
}

//an example
$new_array = array('one','two','break','three',
'break','four','five','six');

var_dump(array_split('break',$new_array));

/*this returns:
array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(3) "one"
    [1]=>
    string(3) "two"
  }
  [1]=>
  array(1) {
    [0]=>
    string(5) "three"
  }
  [2]=>
  array(3) {
    [0]=>
    string(4) "four"
    [1]=>
    string(4) "five"
    [2]=>
    string(3) "six"
  }
}
*/
?>
ktaufik(at)gmail(dot)com
16-Feb-2005 01:31
For you who works for localized "say" number to letter ( ex , 7=> seven, 8=>eight) for Bahasa Indonesia.

Indonesia "say" or "Terbilang" is based on 3 digit number.
thousands, millions and trillions .... will be based on the 3 digit number.

In Indonesia you say 137 as "Seratus Tiga Puluh Tujuh"

<?php
//build random 3 digit number to be "said" in Bahasa Indonesia
$x=rand(0,9);
$y=rand(0,9);
$z=rand(0,9);

function
display_angka_bilangan($n) {
  
$angka = array(
    
1 => 'satu',
    
2 => 'dua',
    
3 => 'tiga',
    
4 => 'empat',
    
5 => "lima",
    
6 => 'enam',
    
7 => 'tujuh',
    
8 => 'delapan',
    
9 => 'sembilan'
  
);
   return
$angka[$n];
}
// Terbilang X-------Say X
if ($x==1){$terbilangx="seratus ";}
elseif (
$x==0){$terbilangx='';}
else {
$terbilangx=''.display_angka_bilangan($x).' '.'ratus ';}
// Terbilang Y ------Say Y
if ($y==0){$terbilangy='';}
elseif (
$y==1 && $z==1){$terbilangy="sebelas";$terbilangz='';}
elseif (
$y==1 && $z==0){$terbilangy="sepuluh ";$terbilangz='';}
elseif (
$y==1 && $z!==1 &&  $z!==0){$terbilangy=''.display_angka_bilangan($z).' belas ';}
else {
$terbilangy=''.display_angka_bilangan($y).' '.'puluh ';}
// Terbilang z ------Say z
if ($z==0){$terbilangz="";}
elseif (
$z==0 && $y==1){$terbilangz="";}
elseif (
$z==1 && $y==1){$terbilangz="";}
elseif(
$y==0) {$terbilangz="".display_angka_bilangan($z);}
elseif (
$y==1 && $z!==1 &&  $z!==0) {$terbilangz="";}
else {
$terbilangz="".display_angka_bilangan($z);};

$terbilang=$terbilangx.$terbilangy.$terbilangz;
echo
$x.$y.$z." ";
echo
$terbilang;
?>

Hope it is useful
ktaufik(at)gmail(dot)com
tYZ
08-Feb-2005 10:53
In reply to zubfatal, root at it dot dk (25-Nov-2004 02:06):

Instead of writing all those functions you could also use:

array_avg: array_sum($arr) / sizeof($arr);
array_max: max($arr);
array_min: min($arr)
daniel _dot eherbert _at gmail _dot com
02-Feb-2005 06:52
i was unable to use normal means to shift an array element up or down, so i had to write a function to do it... i havent had the chance to test it, but the method is there...

<?
$stuff
[0] = 'a';
$stuff[1] = 'b';
$stuff[2] = 'c';
$stuff[3] = 'd';

function
array_shift($array,$value,$direction = 'up')
{
   
$temp = $array;
   
   
/* search for the value */
   
while ($array_value = current($array))
    {
        if (
$array_value == $value)
        {
           
$key = key($array);
            break;
        }
       
next($array);
    }
   
/* no key */
   
if ( !isset($key) )
    {
        return
false;
    }
   
   
/* check if we are at the top or bottom of the array and want to do an invalid move
       ie: top element up, bottom element down
       - return the original array... */
   
if ( $key == 0 && $direction == 'up' )
    {
        return
$array;
    }
    if (
$key == (count($array)-1) && $direction == 'down' )
    {
        return
$array;
    }
   
   
/* reorder the elements */
   
switch ($direction)
    {
        case
'up':
           
$factor = -1;
            break;
        case
'down':
           
$factor = 1;
            break;
    }

   
$temp[$key+$factor] = $array[$key];
   
$temp[$key] = $array[$key+$factor];
   
   
/* return the ordered array */
   
return $temp;
}
?>

$stuff = array_shift($stuff,'c','up'); - will move c up and b down

$stuff = array_shift($stuff,'a','down'); - will move a down and b up

$stuff = array_shift($stuff,'a','up'); - will return the original array

$stuff = array_shift($stuff,'d','down'); - will return the original array

... if the element value could not be found it probably should return the original array instead of false...
m227(a)poczta.onet.pl
20-Jan-2005 05:18
How to count dimensions in multi-array? (corrected)

previous version didn't work when called more than one time.
($dimcount was preserved from previous call)

This is the way I corrected this:

function countdim($array)
  {
    if (is_array(reset($array)))  
      $return = countdim(reset($array)) + 1;
    else
      $return = 1;
 
    return $return;
  }

This function will return int number of array dimensions.
skopek at mediatac dot com
13-Oct-2004 12:44
I needed a function, that returns the cartesian product of some input-arrays in an array. Here is the function that can do that:
<?php
function array_cartesian_product($arrays) {
   
   
//returned array...
   
$cartesic = array();
   
   
//calculate expected size of cartesian array...
   
$size=(sizeof($arrays)>0)?1:0;
    foreach(
$arrays as $array)
    {
       
$size= $size*sizeof($array);
    }
    for(
$i=0; $i<$size;$i++) {
       
$cartesic[$i] = array();
       
        for(
$j=0;$j<sizeof($arrays);$j++)
        {
           
$current = current($arrays[$j]);
           
array_push($cartesic[$i], $current);   
        }
       
//set cursor on next element in the arrays, beginning with the last array
       
for($j=(sizeof($arrays)-1);$j>=0;$j--)
        {
           
//if next returns true, then break
           
if(next($arrays[$j])) {
                break;
            } else {   
//if next returns false, then reset and go on with previuos array...
               
reset($arrays[$j]);
            }
        }
    }
    return
$cartesic;
}
//example
$arrays[0] = array("a", "b");
$arrays[1] = array("x", "y", "z");
print_r(array_cartesian_product($arrays));
?>

The output is:
Array
(
    [0] => Array
        (
            [0] => a
            [1] => x
        )

    [1] => Array
        (
            [0] => a
            [1] => y
        )

    [2] => Array
        (
            [0] => a
            [1] => z
        )

    [3] => Array
        (
            [0] => b
            [1] => x
        )

    [4] => Array
        (
            [0] => b
            [1] => y
        )

    [5] => Array
        (
            [0] => b
            [1] => z
        )
)
Greets
Jan
davidj at boundlessgallery dot DISLIKESPAM dot com
02-Apr-2004 03:10
A recursive function for flattening nested arrays:

<?php

function flatten_array($array) {
    for(
$x = 0; $x < sizeof($array); $x++) {
       
$element = $array[$x];
        if(
is_array($element)) {
           
$results = flatten_array($element);
            for(
$y = 0; $y < sizeof($results); $y++) {
               
$flat_array[] = $results[$y];
            }
        } else {
           
$flat_array[] = $element;
        }
    }
    return
$flat_array;
}

?>

Example:

<?php

$array
= array("0", "1", array("2", "3", array("4", array("5", "6"), "7", "8")), "9", "10", array("11"), array());
print_r($array);
print_r(flatten_array($array));

?>

Output:

Array
(
    [0] => 0
    [1] => 1
    [2] => Array
        (
            [0] => 2
            [1] => 3
            [2] => Array
                (
                    [0] => 4
                    [1] => Array
                        (
                            [0] => 5
                            [1] => 6
                        )

                    [2] => 7
                    [3] => 8
                )

        )

    [3] => 9
    [4] => 10
    [5] => Array
        (
            [0] => 11
        )

    [6] => Array
        (
        )

)
Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
    [6] => 6
    [7] => 7
    [8] => 8
    [9] => 9
    [10] => 10
    [11] => 11
)
31-Jan-2004 10:29
To remove an element from an array use unset(). Example:
unset($bar['mushroomsoup']);
28-Aug-2003 03:09
Remember that if you want to remove an element from an array, you must use "unset" - Do not set the value to null.
szymon at mazurek dot info
24-Aug-2003 02:46
How to count dimensions in multi-array?
This is the way I do this:

function countdim($array) {
    static $dimcount = 1;
    if (is_array(reset($array))) {
        $dimcount++;
        $return = countdim(reset($array));
    } else {
        $return = $dimcount;
    }
    return $return;
}

This function will return int number of array dimensions.

array_change_key_case> <Sorting Arrays
Last updated: Sat, 07 Jan 2012