search for in the  
<rename_functionarray_change_key_case>
Last updated: Thu, 19 May 2005

III. Array Functions

Introduction

These functions allow you to interact with and manipulate arrays in various ways. Arrays are essential for storing, managing, and operating on sets of variables.

Simple and multi-dimensional arrays are supported, and may be either user created or created by another function. There are specific database handling functions for populating arrays from database queries, and several functions return arrays.

Please see the Arrays section of the manual for a detailed explanation of how arrays are implemented and used in PHP. See also Array operators for other ways how to manipulate the arrays.

Requirements

No external libraries are needed to build this extension.

Installation

There is no installation needed to use these functions; they are part of the PHP core.

Runtime Configuration

This extension has no configuration directives defined in php.ini.

Resource Types

This extension has no resource types defined.

Predefined Constants

The constants below are always available as part of the PHP core.

CASE_LOWER (integer)

CASE_LOWER is used with array_change_key_case() and is used to convert array keys to lower case. This is also the default case for array_change_key_case().

CASE_UPPER (integer)

CASE_UPPER is used with array_change_key_case() and is used to convert array keys to upper case.

Sorting order flags:

SORT_ASC (integer)

SORT_ASC is used with array_multisort() to sort in ascending order.

SORT_DESC (integer)

SORT_DESC is used with array_multisort() to sort in descending order.

Sorting type flags: used by various sort functions

SORT_REGULAR (integer)

SORT_REGULAR is used to compare items normally.

SORT_NUMERIC (integer)

SORT_NUMERIC is used to compare items numerically.

SORT_STRING (integer)

SORT_STRING is used to compare items as strings.

SORT_LOCALE_STRING (integer)

SORT_LOCALE_STRING is used to compare items as strings, based on the current locale. Added in PHP 4.3.12 and 5.0.2.

COUNT_NORMAL (integer)

COUNT_RECURSIVE (integer)

EXTR_OVERWRITE (integer)

EXTR_SKIP (integer)

EXTR_PREFIX_SAME (integer)

EXTR_PREFIX_ALL (integer)

EXTR_PREFIX_INVALID (integer)

EXTR_PREFIX_IF_EXISTS (integer)

EXTR_IF_EXISTS (integer)

EXTR_REFS (integer)

Table of Contents
array_change_key_case -- Returns an array with all string keys lowercased or uppercased
array_chunk -- Split an array into chunks
array_combine --  Creates an array by using one array for keys and another for its values
array_count_values -- Counts all the values of an array
array_diff_assoc -- Computes the difference of arrays with additional index check
array_diff_key -- Computes the difference of arrays using keys for comparison
array_diff_uassoc --  Computes the difference of arrays with additional index check which is performed by a user supplied callback function
array_diff_ukey -- Computes the difference of arrays using a callback function on the keys for comparison
array_diff -- Computes the difference of arrays
array_fill -- Fill an array with values
array_filter --  Filters elements of an array using a callback function
array_flip -- Exchanges all keys with their associated values in an array
array_intersect_assoc -- Computes the intersection of arrays with additional index check
array_intersect_key -- Computes the intersection of arrays using keys for comparison
array_intersect_uassoc -- Computes the intersection of arrays with additional index check, compares indexes by a callback function
array_intersect_ukey -- Computes the intersection of arrays using a callback function on the keys for comparison
array_intersect -- Computes the intersection of arrays
array_key_exists -- Checks if the given key or index exists in the array
array_keys -- Return all the keys of an array
array_map --  Applies the callback to the elements of the given arrays
array_merge_recursive -- Merge two or more arrays recursively
array_merge -- Merge one or more arrays
array_multisort -- Sort multiple or multi-dimensional arrays
array_pad --  Pad array to the specified length with a value
array_pop -- Pop the element off the end of array
array_product --  Calculate the product of values in an array
array_push --  Push one or more elements onto the end of array
array_rand --  Pick one or more random entries out of an array
array_reduce --  Iteratively reduce the array to a single value using a callback function
array_reverse --  Return an array with elements in reverse order
array_search --  Searches the array for a given value and returns the corresponding key if successful
array_shift --  Shift an element off the beginning of array
array_slice -- Extract a slice of the array
array_splice --  Remove a portion of the array and replace it with something else
array_sum --  Calculate the sum of values in an array
array_udiff_assoc -- Computes the difference of arrays with additional index check, compares data by a callback function
array_udiff_uassoc -- Computes the difference of arrays with additional index check, compares data and indexes by a callback function
array_udiff -- Computes the difference of arrays by using a callback function for data comparison
array_uintersect_assoc -- Computes the intersection of arrays with additional index check, compares data by a callback function
array_uintersect_uassoc -- Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
array_uintersect -- Computes the intersection of arrays, compares data by a callback function
array_unique -- Removes duplicate values from an array
array_unshift --  Prepend one or more elements to the beginning of an array
array_values -- Return all the values of an array
array_walk_recursive --  Apply a user function recursively to every member of an array
array_walk --  Apply a user function to every member of an array
array --  Create an array
arsort --  Sort an array in reverse order and maintain index association
asort -- Sort an array and maintain index association
compact --  Create array containing variables and their values
count -- Count elements in an array, or properties in an object
current -- Return the current element in an array
each --  Return the current key and value pair from an array and advance the array cursor
end --  Set the internal pointer of an array to its last element
extract --  Import variables into the current symbol table from an array
in_array -- Checks if a value exists in an array
key -- Fetch a key from an associative array
krsort -- Sort an array by key in reverse order
ksort -- Sort an array by key
list --  Assign variables as if they were an array
natcasesort --  Sort an array using a case insensitive "natural order" algorithm
natsort --  Sort an array using a "natural order" algorithm
next --  Advance the internal array pointer of an array
pos -- Alias of current()
prev -- Rewind the internal array pointer
range --  Create an array containing a range of elements
reset --  Set the internal pointer of an array to its first element
rsort -- Sort an array in reverse order
shuffle -- Shuffle an array
sizeof -- Alias of count()
sort -- Sort an array
uasort --  Sort an array with a user-defined comparison function and maintain index association
uksort --  Sort an array by keys using a user-defined comparison function
usort --  Sort an array by values using a user-defined comparison function


User Contributed Notes
Array Functions
a dot lang at freenet dot de
11-May-2005 01:36
With help of this function you can save a whole db in an Array.
Usage:
$sql = mysql_query("SELECT * FROM DB");
$dbarray = sqlar($sql);

function sql2ar ($sql, $return = true)
{
$sql2 = mysql_fetch_assoc($sql);
$befehl ="";
$keys = array_keys($sql2);

   for($i2 = 0;$i2 < count($keys);$i2++)
       {
           $befehl .= '$array[$i][\''.$keys[$i2].'\'] = $row[\''.$keys[$i2].'\'];';
       }
mysql_data_seek($sql,0);
$i = 0;

   while($row = mysql_fetch_assoc($sql))
     {
         eval($befehl);
         $i++;
     }
   if($return == true)
       {
           return $array;
       }
   else
       {
           echo "<pre>";
           print_r($array);
           echo "</pre>";
       }
}
freetools at stocklumino dot com
03-May-2005 07:54
Hi
a sample code for storing an exif data in array, and they reading the data by key name.

//call the functions here
$filename = 'C:\myapp\test.jpg';
testreader($filename,'FileSize');
/*
this is function for test
*/
function testreader($filename,$keytofind)
{
   $allkeyvalsglobal = array();

   $myexif = new exifReader();
   $allkeyvalsglobal = $myexif->manageexifreader($filename);
   $result = $myexif->readExif($allkeyvalsglobal,$keytofind);
   echo "<br>".$keytofind."=".$result;
}

class exifreader
{
  

   function manageexifreader($filename)
   {
       $allkeys = array();
       $keyvalpairs = array();

       $allData = read_exif_data ($filename);
       while(list($k,$v)=each($allData))
       {
           echo "$k: $v<br>\n";
           array_push($allkeys,$k);
           $keyvalpairs[$k] = $v;
       }
       /* Uncomment this for testing
       $foundFileNum = count($allkeys);
       for($i=0;$i<$foundFileNum;$i++)
       {
           $onekey = $allkeys[$i];
               echo"<br>".":".$keyvalpairs[$onekey];
       }*/
       return $keyvalpairs;
   }
  

   function getAllExitdata($filename)
   {
       $exif = read_exif_data ($filename);
   }

   function readExif($allkeyvalsglobal,$keyname)
   {
       //global $allkeyvalsglobal;
       /* Uncomment this for testing
         echo "<br>Got data111 :".$allkeyvalsglobal[$keyname];
       */
       return $allkeyvalsglobal[$keyname];
   }

}
casey geene
30-Apr-2005 05: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 10: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 10: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"
  }
}
*/
?>
14-Apr-2005 08:20
You should really read http://www.php.net/manual/en/language.types.array.php , 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.
ktaufik(at)gmail(dot)com
16-Feb-2005 06: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 03: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
01-Feb-2005 11: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 10: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.
zubfatal, root at it dot dk
25-Nov-2004 07:06
Just a few array functions:

array_avg($arrInput)
Returns the average value of alle numeric values in an array.

<?php

function array_avg($arrInput = NULL) {
   if ((!
is_array($arrInput)) || (!count($arrInput) > 0)) {
       return
"ERR: \$arrInput is empty, or not an array.";
   }
  
   else {
       unset(
$arrTmp);
      
       foreach(
$arrInput as $key => $value) {
           if ((
is_numeric($value)) || (is_float($value)) || (is_int($value))) {
              
$arrTmp[$key] = $value;
           }
       }
      
       if (
is_array($arrTmp)) { return floatval((array_sum($arrTmp) / count($arrTmp))); }
       else { return
"ERR: No numeric values found."; }
   }
}
?>

array_max($arrInput)
Returns the maximum value of all the numeric values in an array.

<?php
function array_max($arrInput = NULL) {
   if ((!
is_array($arrInput)) || (!count($arrInput) > 0)) {
       return
"ERR: \$arrInput is empty, or not an array.";
   }
  
   else {
       unset(
$arrTmp);
      
       foreach(
$arrInput as $key => $value) {
           if ((
is_numeric($value)) || (is_int($value))) {
              
$arrTmp[$key] = $value;
           }
       }
      
       if (
is_array($arrTmp)) {
          
sort($arrTmp, SORT_NUMERIC);
           return
array_pop($arrTmp);
       }
      
       else {
           return
"ERR: No numeric values found.";
       }
   }
}

?>

array_min($arrInput)
Just the opposite of array_max ;) - returns the minimum value of all the numeric values in an array.

<?php
function array_min($arrInput = NULL) {
   if ((!
is_array($arrInput)) || (!count($arrInput) > 0)) {
       return
"ERR: \$arrInput is empty, or not an array.";
   }
  
   else {
       unset(
$arrTmp);
      
       foreach(
$arrInput as $key => $value) {
           if ((
is_numeric($value)) || (is_int($value))) {
              
$arrTmp[$key] = $value;
           }
       }
      
       if (
is_array($arrTmp)) {
          
rsort($arrTmp, SORT_NUMERIC);
           return
array_pop($arrTmp);
       }
      
       else {
           return
"ERR: No numeric values found.";
       }
   }
}
?>

// zubfatal
Ollie Maitland <ollieatbyng-designs.com>
22-Nov-2004 11:08
I have had some trouble finding a function to convert php arrays to JavaScript so I wrote a small function to deal with multidimensional associative arrays ( i couldn't see how to modify gigi at orsone dot com one) :

So using gigi at orsone dot com one array it like this:

<?php
function array_php2js($data,$pre) {

  foreach(
$data as $k => $v) {
  
  
$rt .=$pre."['".$k."']";
   if(
is_array($v)) $a[] = "".$rt."=new Array (".count($v).")"; $a = array_merge($a,array_php2js($v,$rt));
   if(
is_string($v)) $a[] ="".$rt."=".$v."";
  
$rt="";

  }
  return
$a;
}

$menuz =
  array(
'Products', 'products.php',
   array(
'Fruit', null,
         array(
'Bananas', 'products.php?cat=bananas'),
         array(
'Apples', 'products.php?cat=apples'),
         array(
'Lemons', 'products.php?cat=lemons')
       ),
       array(
'Chocolate', 'products.php?cat=chocolate')
  );
//the <br /> is just for formatting
print (implode (";\n<br />",array_php2js($menuz,'menus')).";\n");
}

?>

This would produce:

menus['0']=Products;
menus['1']=products.php;
menus['2']=new Array (5);
menus['2']['0']=Fruit;
menus['2']['2']=new Array (2);
menus['2']['2']['0']=Bananas;
menus['2']['2']['1']=products.php?cat=bananas;
menus['2']['3']=new Array (2);
menus['2']['3']['0']=Apples;
menus['2']['3']['1']=products.php?cat=apples;
menus['2']['4']=new Array (2);
menus['2']['4']['0']=Lemons;
menus['2']['4']['1']=products.php?cat=lemons;
menus['3']=new Array (2);
menus['3']['0']=Chocolate;
menus['3']['1']=products.php?cat=chocolate;

Hope this helps.

- Ollie Maitland
sd dot admin at cosmosgaming dot com
20-Nov-2004 04:59
The functions above depict how functions can be used when arrays need to be put into a function which would have one result.

I would like to clarify on the fact that only one result or output can exist for a function. This conspicuously is a restatement of an inference from the definition of a function.

To handle a MySQL connnection function, it is thus obvious that both connection and database retrieval cannot be done through one function, which was one of my goals. My recommendation, however, for dealing with this type of work, is to simply have one function to connect, which would look like this:

function mysqldatabaseconnection($host, $hostuser, $hostpass, $db, $error)
{
   $link = mysql_connect($host, $hostuser, $hostpass) or die($error . "Connection failed: " . mysql_error());
   // echo "Connected successfully";
   mysql_select_db($db) or die($error . "Selection of database failed: " . mysql_error());
   // $dbconnectset=array(dblink => $link, result => $result); As seen here the retrieval was done here too, but that was cut out for time-saving
   return $link;
}

To connect from inside the HTML page, use this:

$link = mysqldatabaseconnection($host, $hostuser, $hostpass, $db, $error);

Afterwards the retrieval of data can be pursued with techniques as seen on http://us2.php.net/manual/en/function.mysql-fetch-array.php.

Finally, and of some high degree of significance, the connection can be closed, since the link exists, with:

mysql_close($link);
27-Oct-2004 05:29
/*! \fn array_renamekeys($values, $table)
   *  \brief Renames the array keys of an array
   *
   *  $table = array ( "<old_value" => "new_value", ... )
   */
   function array_renamekeys($values, $table)
   {
     if (is_array($values))
     {
         foreach($values as $k => $v)
         {
           if (strlen($table["$k"])>0)
           {
               unset($values["$k"]);
               $k=$table["$k"];
           }

           if (is_array($v))
           {
               $values["$k"]=$this->array_renamekeys($v, $table);
           }
           else
           {
               $values["$k"]=$v;
           }
         }
     }
     return $values;
   }
skopek at mediatac dot com
13-Oct-2004 05: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
hadi_rastgou at yahoo dot com
11-Oct-2004 11:57
A recursive function for TRNSFORMING  nested arrays to a STRING:

#This recursive function transforms array indexs
#and their vlaues to a string

function array_to_str($array){
   $str_of_array_keys_n_vals = "";
   foreach($array as $key=>$val){
       if(is_array($val)){
           $str_of_array_keys_n_vals .= "[$key = {". array_to_str($val)."}] , ";
       }
       else{
           $str_of_array_keys_n_vals .= "[$key=$val] , ";
       }
   }
  
   return substr($str_of_array_keys_n_vals, 0, strlen($str_of_array_keys_n_vals)-3);
}

Array (
   [ou] => My Test
   [description] => ee
   [objectclass] => Array (
                     [0] => top
                     [1] => organizationalunit
                               )
       )

Will be

[ou=My Test] , [description=ee] , [objectclass = {[0=top] , [1=organizationalunit]}]
reverse esacdaehasinhoj at oohay dot moc
28-Jun-2004 05:39
I've included a neat function I had to hack out, to handle exploding on multiple strings as tokens without losing which token created the break.  There's lots of room for improvement; this function has bad behavior when tokens overlap, for instance, and doesn't provide any way to discover what tokens occurred in what order (though, token order for a given delimiter is preserved.)  Should there be a piece of string before any delimiters, or should there be no delimiter, the remainder will be stored in the result's index for null string.

Case sensitivity control is dependant on stripos(), which is only available in PHP5 CVS.  PHP<5 may only use this function case sensitively unless a replacement is provided.

<?php

 
// function has incorrect results when delimiters overlap
 
function mexplode_dangerous($delimiters, $data, $casesensitive = true) {
    
$points = array();
     foreach (
$delimiters as $delim) {
        
$nextpoint = 0;
         if (
$casesensitive) {
               while (!( (
$point = strpos($data, $delim, $nextpoint)) === false )) {
                  
$points[$point] = $delim;
                  
$nextpoint = $point + strlen($delim);
               }
         } else {
               while (!( (
$point = stripos($data, $delim, $nextpoint)) === false )) {
                  
$points[$point] = $delim;
                  
$nextpoint = $point + strlen($delim);
               }
         }
     }

     if (
count($points) == 0) {

         return array(
'' => $data);

     } else {

        
$start=strlen($data);
        
reset($points);
        
krsort($points);

         while (
$point = current($points)) {
            
$offset = key($points) + strlen($point);
            
$result[$point][] = substr($data, $offset, $start-$offset);
            
$start=key($points);
            
next($points);
         }

        
reset($result);
         while(
$row = current($result)) {
            
$output[key($result)] = array_reverse($row);
            
next($result);
         }

        
$output['']=substr($data,0,$start);

         return
$output;

     }
  }

 
// Usage is fairly straightforward.

 
print_r(mexplode_dangerous(array('@','=','::','|'), 'hello@at1=eq1::colon1|pipe1|pipe2|pipe3::colon2::colon3=eq2@at2'));

?>

This should return:

Array
(
   [@] => Array
       (
           [0] => at1
           [1] => at2
       )

   [=] => Array
       (
           [0] => eq1
           [1] => eq2
       )

   [::] => Array
       (
           [0] => colon1
           [1] => colon2
           [2] => colon3
       )

   [|] => Array
       (
           [0] => pipe1
           [1] => pipe2
           [2] => pipe3
       )

   [] => hello
)
brooklynphil hotmail com
21-Jun-2004 05:19
was browsing, and saw some array flattening functions... then i remembered i wrote one a while ago, and i wanted to compare code. to my surprise, the code was basically the same, except my code preserves keys:
<?php function array_flatten(&$a,$pref='') {
  
$ret=array();
   foreach (
$a as $i => $j)
       if (
is_array($j))
          
$ret=array_merge($ret,array_flatten($j,$pref.$i));
       else
          
$ret[$pref.$i] = $j;
   return
$ret;
   }
?>

the flattened array will have its numerical keys converted to strings, however, due to a glitch* in php, these string keys might be converted back to integers!

<?php $qqq= array(array(array(12)),array(56),array(14,1));
pretty($qqq);
pretty(array_flatten($qqq));?>

will render:

<?php
/*array(3){[0]=>array(1){[0]=>array(1){[0]=>int(12)}}
[1]=>array(1){[0]=>int(56)  }
[2]=>array(2){[0]=>int(14)
   [1]=>int(1)}
}
array(4) {  ["000"]=>  int(12)
  [0]=>  int(56)
  [1]=>  int(14)
  [2]=>  int(1)}*/
?>

as you can see the firsrt array 'tree' is flattened successfully, because "000" does not convert to 0, but the subsequent 'tree's are converted from e.g. "10" to 0... (why 0? i would have thought 10)

seeding the prefix with something that forces a string conversion, alleviates this problem (and shows that its not my code, per se):

<?php
var_dump
(array_flatten($qqq,"~"));
/*array(4) {
  ["~000"]=>  int(12)
  ["~10"]=>  int(56)
  ["~20"]=>  int(14)
  ["~21"]=>  int(1)}*/
?>

--Phil

* not really sure if this is a glitch.  here is what the manual says:
<?php /* A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). There are no different indexed and associative array types in PHP; there is only one array type, which can both contain integer and string indices. */ ?>
in http://www.php.net/manual/en/language.types.array.php
is there any way to circumvent this behaviour and force string keys? ive tried casting to no avail...
Minots Estichá <minots at d0x dot de>
22-May-2004 12:10
Sometimes it´s usefull to trim all values from a given array.
I wrote this function ( array_trim ) to do it for me:

<?php
function array_trim(&$arr)
{
  while (list(
$key,$val)=each($arr)):
   if ( (
strtoupper($key) != $key or ''.intval($key) == "$key") && $key != "argc" and $key != "argv"):
       if (
is_string($val)):
          
$arr[$key] = trim($val);
       endif;
       if (
is_array($val)):
          
$arr[$key] = array_trim($val);
       endif;
   endif;
  endwhile;
  return
$arr;
}
?>

If there is a better way, feel free to send me a note via
feedback-formular at http://www.d0x.de/pages/kontakt.php .
gigi at orsone dot com
25-Apr-2004 12:30
Here is a small function to "convert" php arrays to javascript...
<?php
$menuz
=
  array(
'Products', 'products.php',
   array(
'Fruit', null,
         array(
'Bananas', 'products.php?cat=bananas'),
         array(
'Apples', 'products.php?cat=apples'),
         array(
'Lemons', 'products.php?cat=lemons')
       ),
       array(
'Chocolate', 'products.php?cat=chocolate')
  );

 
function
array_php2js($data) {
  foreach(
$data as $k=>$datum) {
   if(
is_null($datum)) $data[$k] = 'null';
   if(
is_string($datum)) $data[$k] = "'" . $datum . "'";
   if(
is_array($datum)) $data[$k] = php2js($datum);
  }
  return
"[" . implode(', ', $data) . "]";
}
print(
array_php2js($menuz));
?>

And you get:

['Products', 'products.php', ['Fruit', null, ['Bananas', 'products.php?cat=bananas'], ['Apples', 'products.php?cat=apples'], ['Lemons', 'products.php?cat=lemons']], ['Chocolate', 'products.php?cat=chocolate']]
I find it useful in many situation... ;)
esbjorn
22-Apr-2004 07:18
A shorter recursive function to flatten nested arrays could be:

function flattenArray($array)
{
   $flatArray = array();
   foreach( $array as $subElement ) {
       if( is_array($subElement) )
           $flatArray = array_merge($flatArray, flattenArray($subElement));
       else
           $flatArray[] = $subElement;
   }
   return $flatArray;
}
davidj at boundlessgallery dot DISLIKESPAM dot com
01-Apr-2004 07: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
)
webmaster at pzfn dot com
15-Mar-2004 09:15
You should be able to do this....

<?
function unset_by_val($needle,&$haystack) {
 
$haystack = array_flip($haystack);
  unset(
$haystack[$needle]);
 
$haystack = array_flip($haystack);
  return
$haystack;
}
?>
31-Jan-2004 04:54
unset($bar['mushroomsoup']) only works it the key
is 'mushroomsoup'.If you want to erase elements
of an array identified by values rather than by keys
you can use this function:
<?
function unset_by_val($needle,&$haystack) {
# removes all entries in array $haystack,
# who's value is $needle
 
while(($gotcha = array_search($needle,$haystack)) > -1)
   unset(
$haystack[$gotcha]);
}
 
$ring = array('gollum','smeagol','gollum','gandalf',
                    
'deagol','gandalf');
 
print_r($ring); echo "<br>";
 
unset_by_val('gollum',$ring);
 
print_r($ring);
?>
Will output:
Array ( [0] => gollum [1] => smeagol [2] => gollum
  [3] => gandalf [4] => deagol [5] => gandalf )
Array ( [1] => smeagol [3] => gandalf
  [4] => deagol [5] => gandalf )
31-Jan-2004 03:29
To remove an element from an array use unset(). Example:
unset($bar['mushroomsoup']);
28-Aug-2003 08: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 07: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.
jeroen at php dot net
29-Aug-2001 03:58
You should really read http://www.php.net/manual/en/language.types.array.php , 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.

<rename_functionarray_change_key_case>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT