V. Array 数组函数

简介

本类函数允许用多种方法来操作数组和与之交互。数组的本质是储存,管理和操作一组变量。

PHP 支持一维和多维数组,可以是用户创建或由另一个函数创建。有一些特定的数据库处理函数可以从数据库查询中生成数组,还有一些函数返回数组。

参见手册中的数组一节关于 PHP 是怎样实现和使用数组的详细解释。参见数组运算符一节关于怎样操作数组的其它方法。

需求

要编译本扩展模块不需要外部库文件。

安装

本函数库作为 PHP 内核的一部分,不用安装就能使用。

运行时配置

本扩展模块在 php.ini 中未定义任何配置选项。

资源类型

本扩展模块未定义任何资源类型。

预定义常量

以下常量作为 PHP 核心的一部分一直有效。

CASE_LOWER (integer)

CASE_LOWER 用在 array_change_key_case() 中将数组的键名转换成小写字母。这也是 array_change_key_case() 的默认值。

CASE_UPPER (integer)

CASE_UPPER 用在 array_change_key_case() 中将数组的键名转换成大写字母。

排序顺序标识:

SORT_ASC (integer)

SORT_ASC 用在 array_multisort() 函数中,使其升序排列。

SORT_DESC (integer)

SORT_DESC 用在 array_multisort() 函数中,使其降序排列。

排序类型标识:用于各种排序函数

SORT_REGULAR (integer)

SORT_REGULAR 用于对对象进行通常比较。

SORT_NUMERIC (integer)

SORT_NUMERIC 用于对对象进行数值比较。

SORT_STRING (integer)

SORT_STRING 用于对对象进行字符串比较。

SORT_LOCALE_STRING (integer)

SORT_LOCALE_STRING 基于当前区域来对对象进行字符串比较。PHP 4.4.0 和 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)

参见

参见 is_array()explode()implode()split()preg_split()unset()

【译者注】本章中出现的“关联数组”或“结合数组”指的是键名为字符串的数组,“索引”和“键名”指的是同一样东西。“索引”多指数组的数字形式的下标。

目录
array_change_key_case -- 返回字符串键名全为小写或大写的数组
array_chunk -- 将一个数组分割成多个
array_combine --  创建一个数组,用一个数组的值作为其键名,另一个数组的值作为其值
array_count_values -- 统计数组中所有的值出现的次数
array_diff_assoc -- 带索引检查计算数组的差集
array_diff_key -- 使用键名比较计算数组的差集
array_diff_uassoc -- 用用户提供的回调函数做索引检查来计算数组的差集
array_diff_ukey -- 用回调函数对键名比较计算数组的差集
array_diff -- 计算数组的差集
array_fill -- 用给定的值填充数组
array_filter --  用回调函数过滤数组中的单元
array_flip -- 交换数组中的键和值
array_intersect_assoc -- 带索引检查计算数组的交集
array_intersect_key -- 使用键名比较计算数组的交集
array_intersect_uassoc -- 带索引检查计算数组的交集,用回调函数比较索引
array_intersect_ukey -- 用回调函数比较键名来计算数组的交集
array_intersect -- 计算数组的交集
array_key_exists -- 检查给定的键名或索引是否存在于数组中
array_keys -- 返回数组中所有的键名
array_map --  将回调函数作用到给定数组的单元上
array_merge_recursive -- 递归地合并一个或多个数组
array_merge -- 合并一个或多个数组
array_multisort -- 对多个数组或多维数组进行排序
array_pad --  用值将数组填补到指定长度
array_pop -- 将数组最后一个单元弹出(出栈)
array_product -- 计算数组中所有值的乘积
array_push --  将一个或多个单元压入数组的末尾(入栈)
array_rand --  从数组中随机取出一个或多个单元
array_reduce -- 用回调函数迭代地将数组简化为单一的值
array_reverse --  返回一个单元顺序相反的数组
array_search --  在数组中搜索给定的值,如果成功则返回相应的键名
array_shift --  将数组开头的单元移出数组
array_slice -- 从数组中取出一段
array_splice --  把数组中的一部分去掉并用其它值取代
array_sum --  计算数组中所有值的和
array_udiff_assoc -- 带索引检查计算数组的差集,用回调函数比较数据
array_udiff_uassoc -- 带索引检查计算数组的差集,用回调函数比较数据和索引
array_udiff -- 用回调函数比较数据来计算数组的差集
array_uintersect_assoc -- 带索引检查计算数组的交集,用回调函数比较数据
array_uintersect_uassoc -- 带索引检查计算数组的交集,用回调函数比较数据和索引
array_uintersect -- 计算数组的交集,用回调函数比较数据
array_unique -- 移除数组中重复的值
array_unshift --  在数组开头插入一个或多个单元
array_values -- 返回数组中所有的值
array_walk_recursive -- 对数组中的每个成员递归地应用用户函数
array_walk -- 对数组中的每个成员应用用户函数
array --  新建一个数组
arsort --  对数组进行逆向排序并保持索引关系
asort -- 对数组进行排序并保持索引关系
compact --  建立一个数组,包括变量名和它们的值
count -- 计算数组中的单元数目或对象中的属性个数
current -- 返回数组中的当前单元
each --  返回数组中当前的键/值对并将数组指针向前移动一步
end --  将数组的内部指针指向最后一个单元
extract --  从数组中将变量导入到当前的符号表
in_array -- 检查数组中是否存在某个值
key -- 从关联数组中取得键名
krsort -- 对数组按照键名逆向排序
ksort -- 对数组按照键名排序
list --  把数组中的值赋给一些变量
natcasesort --  用“自然排序”算法对数组进行不区分大小写字母的排序
natsort --  用“自然排序”算法对数组排序
next --  将数组中的内部指针向前移动一位
pos -- current() 的别名
prev -- 将数组的内部指针倒回一位
range --  建立一个包含指定范围单元的数组
reset --  将数组的内部指针指向第一个单元
rsort -- 对数组逆向排序
shuffle -- 将数组打乱
sizeof -- count() 的别名
sort -- 对数组排序
uasort --  使用用户自定义的比较函数对数组中的值进行排序并保持索引关联
uksort --  使用用户自定义的比较函数对数组中的键名进行排序
usort --  使用用户自定义的比较函数对数组中的值进行排序

add a note add a note User Contributed Notes
zspencer at zacharyspencer dot com
01-Nov-2006 10: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 09: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 08: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
)
Binny V A
06-Oct-2006 03:17
A small function to remove an element from a list(numerical array)

<?php
function array_remove($arr,$value) {
   return
array_values(array_diff($arr,array($value)));
}
?>

Or, if you don't like that...

<?php
function array_remove($arr,$value) {
   if(!
in_array($value,$arr)) return $arr;
   unset(
$arr[array_search($value,$arr)]);
   return
array_values($arr);
}
?>

Binny V A
http://www.bin-co.com/php/
kthejoker - google mail
21-Sep-2006 01: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 06: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 11: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 08: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 07: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 07: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 08: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
11-Aug-2006 03: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 11: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
20-Jul-2006 04: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 08: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 09: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
07-Jun-2006 04: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
28-May-2006 03: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
14-Apr-2006 05: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 06: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 08: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
25-Mar-2006 06: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
19-Mar-2006 06: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
15-Mar-2006 01:08
Re removing blank elements from arrays, this is even more concise:

<?php

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

?>
Nimja
23-Feb-2006 11: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
06-Feb-2006 04: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
01-Feb-2006 06: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
20-Jan-2006 01: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 09: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 09: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
02-Jan-2006 12: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 10: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
25-Nov-2005 01: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 05: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 11: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 04: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 09: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 09: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 04:32
To convert an array to a HTML table, see:
http://aidan.dotgeek.org/repos/?file=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 11: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
16-Aug-2005 02: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 07: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 08: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
09-Jul-2005 04: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 06: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 11: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 11: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 08: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
09-Feb-2005 05: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 01: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
21-Jan-2005 12: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 06: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 09: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
)
01-Feb-2004 05:29
To remove an element from an array use unset(). Example:
unset($bar['mushroomsoup']);
28-Aug-2003 09: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 08: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.