 |
V. Array 数组函数
本类函数允许用多种方法来操作数组和与之交互。数组的本质是储存,管理和操作一组变量。
PHP 支持一维和多维数组,可以是用户创建或由另一个函数创建。有一些特定的数据库处理函数可以从数据库查询中生成数组,还有一些函数返回数组。
参见手册中的数组一节关于
PHP 是怎样实现和使用数组的详细解释。参见数组运算符一节关于怎样操作数组的其它方法。
本扩展模块作为 PHP 内核的一部分,无需安装即可使用。 本扩展模块在 php.ini 中未定义任何配置选项。 以下常量作为 PHP 核心的一部分一直有效。
排序顺序标识:
排序类型标识:用于各种排序函数
- 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 新加。
pedja at uzice dot net
07-Aug-2007 12:38
Here is the function that cleans array of empty records. It goes recursive through multidimensional array and erases any item that has empty value or is empty array.
This actually works on any variable type, not just arrays.
<?php
function clean_item ($p_value) {
if (is_array ($p_value)) {
if ( count ($p_value) == 0) {
$p_value = null;
} else {
foreach ($p_value as $m_key => $m_value) {
$p_value[$m_key] = clean_item ($m_value);
if (empty ($p_value[$m_key])) unset ($p_value[$m_key]);
}
}
} else {
if (empty ($p_value)) {
$p_value = null;
}
}
return $p_value;
}
?>
Example:
<?php
$m_array['aaa'] = 'bbb';
$m_array['ccc'] = '';
$m_array['ddd'] = Array();
$m_array['eee']['fff'] = Array();
$m_array['eee']['ggg'] = '';
$m_array['eee']['hhh'] = 'iii';
$m_array['eee']['j']['a'] = 'gh';
$m_array['eee']['j']['b'] = '';
$m_array['eee']['j']['c'] = 'rty';
$m_array['eee']['j']['d'] = Array();
$m_array['eee']['j']['e'][1] = 'r';
$m_array['eee']['j']['e'][2] = 'y';
$m_array['eee']['j']['e'][1] = '';
$m_array['eee']['j']['e'][4] = Array();
$m_array['eee']['j']['e'][5] = '';
$m_clean = $seo->clean_item ($m_array);
print_r ($m_array);
print_r ($m_clean);
?>
Variable $m_clean contains:
Array
(
[aaa] => bbb
[eee] => Array
(
[hhh] => iii
[j] => Array
(
[a] => gh
[c] => rty
[e] => Array
(
[2] => y
)
)
)
)
?>
mo dot longman at gmail dot com
31-Jul-2007 06:27
to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.
to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);
You can also stringify objects, numbers, etc.
g4wx3
19-Jul-2007 09:16
I needed a function to convert a php array into a javascript array.
No problem i found it on "the net".
But the function i found wasn't good enough, instead of return a string with javascript-array it echoed directly everything.
I wanted to write the string to a file, when calling the function out of my function libary.
Secondly, there where minor "bugs" in the script, when you're original array contained characters like line breaks(\r\n,..), or quotes('), it would hack up the javascript array
Sow, i changed the function and fixed the bug.
<?php
//SUPER COOL : http://www.communitymx.com/content/article.cfm?page=3&cid=7CD16
//Checkout: REVERSE: http://www.hscripts.com/tutorials/php/jsArrayToPHP.php
//Convert a PHP array to a JavaScript one (rev. 4)
//Changlog by g4wx3: echo replaced by $output, added function output
function output($string) //make javascript ready
{
$string = str_replace( array( '\\' , '\'' ), array('\\\\', '\\\'') , $string); //-> for javascript array
$string = str_replace( array("\r\n", "\r", "\n") , '<br>' , $string); //nl2br
return $string;
}
function arrayToJS4($array, $baseName ) {
//Write out the initial array definition
//v4 echo ($baseName . " = new Array(); \r\n ");
$output = $baseName . " = new Array(); \r\n ";
//Reset the array loop pointer
reset ($array);
//Use list() and each() to loop over each key/value
//pair of the array
while (list($key, $value) = each($array)) {
if (is_numeric($key)) {
//A numeric key, so output as usual
$outKey = "[" . $key . "]";
} else {
//A string key, so output as a string
$outKey = "['" . $key . "']";
}
if (is_array($value)) {
//The value is another array, so simply call
//another instance of this function to handle it
$output .= arrayToJS4($value, $baseName . $outKey);
} else {
//Output the key declaration
//v4 echo ($baseName . $outKey . " = ");
$output .= $baseName . $outKey . " = ";
//Now output the value
if (is_string($value)) {
//Output as a string, as we did before
//v4 echo ("'" . output($value) . "'; \r\n ");
$output .= "'" . output($value) . "'; \r\n ";
} else if ($value === false) {
//Explicitly output false
//v4 echo ("false; \r\n");
$output .= "false; \r\n";
} else if ($value === NULL) {
//Explicitly output null
//v4 echo ("null; \r\n");
$output .= "null; \r\n";
} else if ($value === true) {
//Explicitly output true
//v4 echo ("true; \r\n");
$output .= "true; \r\n";
} else {
//Output the value directly otherwise
//v4 echo ($value . "; \r\n");
$output .= $value . "; \r\n";
}
}
}
return $output;
}
?>
You can use this for printing $_GET array, for example
shufty at gmail dot com
19-Jul-2007 02:20
when using Nimja's function, it was removing values that equaled 0, the following function counters this
<?php
function cleanArray($array) {
foreach ($array as $key => $value) {
if ($value == "") unset($array[$key]);
}
return $array;
}
?>
phamphong_tn at yahoo dot com
28-Jun-2007 11:34
This is a code remove an other row of array
<?php
//$mang is an array, $id is index of row in array
function remove($mang,$id)
{
$flag = false;
$count = count($mang);
$i = 0;
while ($flag!=true && $i<$count) {
if ($i==$id) {
unset($mang[$i]);
$flag = true;
$index = $i;
}
else {
if ($temp) {
array_push($temp,$mang[$i]);
}
else
{
$temp = array($mang[$i]);
}
}
$i++;
}
if ($flag) {
while ($index<$count)
{
if ($temp) {
array_push($temp,$mang[$index+1]);
}
else
{
$temp = array($mang[$index+1]);
}
$index++;
}
}
array_pop($temp);
return $temp;
}
$arr = array(array("id"=>"1","name"=>"b"),array("id"=>"2","name"=>"d"));
array_push($arr,array("id"=>"3","name"=>"f"));
array_push($arr,array("id"=>4,"name"=>"g"));
$arr = remove($arr,2);
echo "<pre>";
print_r($arr);
?>
peanutpad at msn dot com
15-Jun-2007 10:15
heres a function from http://www.linksback.org Feedback welcome, of course! Public domain, yadda yadda.
function mySort(&$array,$key) {
if (!is_array($array) || count($array) == 0) return true;
$assocSortCompare = '$a = $a["'.$key.'"]; $b = $b["'.$key.'"];';
if (is_numeric($array[0][$key])) {
$assocSortCompare.= ' return ($a == $b) ? 0 : (($a < $b) ? -1 : 1);';
} else {
$assocSortCompare.= ' return strcmp($a,$b);';
}
$assocSortCompare = create_function('$a,$b',$assocSortCompare);
return usort($array,$assocSortCompare);
}
webdev at svbeatrix dot com
11-Jun-2007 04:06
Bugs happen, but how can people post functions that WON'T EVEN COMPILE! I truly detest finding a cool code snippet or function and then having to debug them. Sorry for the rant, but I have experienced this scenario a number of times. TEST YOUR CODE, THEN POST!
Here is a revised and corrected previously posted function ArrayDepth, which had 3 bugs and yes, would not compile.
function ArrayDepth($Array,$DepthCount=-1) {
// Find maximum depth of an array
// Usage: int ArrayDepth( array $array )
// returns integer with max depth
// if Array is a string or an empty array it will return 0
$DepthArray=array(0);
$DepthCount++;
$Depth = 0;
if (is_array($Array))
foreach ($Array as $Key => $Value) {
$DepthArray[]=ArrayDepth($Value,$DepthCount);
}
else
return $DepthCount;
return max($DepthCount,max($DepthArray));
}
sean at aliencreations dot com
09-Jun-2007 11:36
I wrote this function to parse arrays so they work with SQL strings if you need to use the MySQL "IN()" function.
function format_sql_array($array)
{
$SQLstring = "";
foreach($array as $item)
{
$SQLstring .= "'$item',";
}
$SQLstring = rtrim($SQLstring, ",");
$SQLstring = str_replace("'',", "", $SQLstring);
return $SQLstring;
}
Example:
$my_array = array("red", "blue", "green");
$sql_array = format_sql_array($my_array);
//$sql_array is now "'red','blue','green'"
Sample SQL:
$SQL = "SELECT FROM colors_table WHERE color IN($sql_array)";
sid dot pasquale at gmail dot com
29-May-2007 09:57
<?php
/* This function allow you to transform a multidimensional array
in a simple monodimensional array.
Usage: array_walk($oldarray, 'flatten_array', &$newarray);
For example, this code below shows to you:
Array
(
[1] => Array
(
[0] => 1
[1] => 2
)
[2] => Array
(
[0] => 3
[1] => 4
)
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
*/
function flatten_array($value, $key, &$array) {
if (!is_array($value))
array_push($array,$value);
else
array_walk($value, 'flatten_array', &$array);
}
$oldarray = array(
1 => array(1,2),
2 => array(3,4)
);
$newarray = array();
array_walk($oldarray, 'flatten_array', &$newarray);
echo "<pre>";
print_r($oldarray);
print_r($newarray);
echo "</pre>";
?>
djspy187 at gmail dot com
16-May-2007 09:05
I had an issue with arrays and copying them by reference as follows.
// Loop on the list and insert default values
foreach ($navigation as &$item)
{
$children = &$item['children']};
foreach ($children as &$child)
{
// Do stuff
}
}
This would give me error message
Fatal error: Cannot create references to/from string offsets nor overloaded objects in /var/www/dev/kh_system/navigation.php on line 103
Even though $item['children'] is an array.
The workaround is to do a for ($i =0;$i < count($Item);$i++) and to then access the children like this
$navigation[$i]['children']
frando
26-Apr-2007 02:14
This is a super-hard array conversion function.
It only returns TRUE if the two arrays are completely identical, that means that they have the same keys, and the values of all keys are exactly the same (compared with ===).
<?php
function array_same($a1, $a2) {
if (!is_array($a1) || !is_array($a2))
return false;
$keys = array_merge(array_keys($a1), array_keys($a2));
foreach ($keys as $k) {
if (!isset($a2[$k]) || !isset($a1[$k]))
return false;
if (is_array($a1[$k]) || is_array($a2[$k])) {
if (!array_same($a1[$k], $a2[$k]))
return false;
}
else {
if (! ($a1[$k] === $a2[$k]))
return false;
}
}
return true;
}
?>
Q1712 at online dot ms
23-Apr-2007 01:34
for your intrest:
the values of the constans used are (all integer):
CASE_LOWER = 0
CASE_UPPER = 1
SORT_ASC = 4
SORT_DESC = 3
SORT_REGULAR = 0
SORT_NUMERIC = 1
SORT_STRING = 2
SORT_LOCALE_STRING = 5
COUNT_NORMAL = 0
COUNT_RECURSIVE = 1
EXTR_OVERWRITE = 0
EXTR_SKIP = 1
EXTR_PREFIX_SAME = 2
EXTR_PREFIX_ALL = 3
EXTR_PREFIX_INVALID = 4
EXTR_PREFIX_IF_EXISTS = 5
EXTR_IF_EXISTS = 6
EXTR_REFS = 256
info at dyflexis dot nl
17-Apr-2007 08:13
A modernized version of the flatten_array() functies written by
davidj at boundlessgallery dot DISLIKESPAM dot com
on 02-Apr-2004 03:10
This function is able to work with associative arrays
<?php
function flatten_array($array) {
$size=sizeof($array);
$keys=array_keys($array);
for($x = 0; $x < $size; $x++) {
$element = $array[$keys[$x]];
if(is_array($element)) {
$results = flatten_array($element);
$sr = sizeof($results);
$sk=array_keys($results);
for($y = 0; $y < $sr; $y++) {
$flat_array[$sk[$y]] = $results[$sk[$y]];
}
} else {
$flat_array[$keys[$x]] = $element;
}
}
return $flat_array;
}
?>
psbrogna at yahoo dot com
17-Apr-2007 03:12
Why is a deep copy function needed to move a sub array? I've just used the equality operator as in the code below.
<?php
$a= array(
'a'=>'apple',
'b'=>'banana',
'c'=>'cherry',
'subArray'=>array(
'A'=>'APPLE',
'B'=>'BANANA',
'C'=>'CHERRY'
)
);
$a['copiedArray']= $a['subArray']; unset($a['subArray']);
var_dump($a);
?>
The above outputs the $a array with copiedArray being present and subArray gone. (php version: 4.4.0).
wmakend at intershop dot de
05-Apr-2007 09:41
if you want to sort array like this one
$aInt = array('1','2','3','4');
and you to have somethings like this
1 --- 2
1 --- 3
1 --- 4
2 --- 3
2 --- 4
3 --- 4
you can do this like with
$NumInt = count($aInt);
for($j=0; $j<=$NumInt-1; $j++){
$first = $aInt[$j];
for ($i=1; $i<=$NumInt-1-$j; $i++) {
echo $first." --- ".$aInt[$i+$j]."<br>";
}
}
info at joolee dot nl
19-Mar-2007 12:49
A slight modification in the arraytostring function, posted below. This function lists an array the same way you would define it in PHP.
<?PHP
function arraytostring($array, $depth = 0)
{
if($depth > 0)
$tab = implode('', array_fill(0, $depth, "\t"));
$text.="array(\n";
$count=count($array);
foreach ($array as $key=>$value)
{
$x++;
if (is_array($value))
{
if(substr($text,-1,1)==')') $text .= ',';
$text.=$tab."\t".'"'.$key.'"'." => ".arraytostring($value, $depth+1);
continue;
}
$text.=$tab."\t"."\"$key\" => \"$value\"";
if ($count!=$x) $text.=",\n";
}
$text.="\n".$tab.")\n";
if(substr($text, -4, 4)=='),),')$text.='))';
return $text;
}
?>
Vladson
14-Mar-2007 03:18
Hope someone find it useful..
<?php
/*
Function: eratosthenes
Usage: array eratosthenes ( int max_value )
Description:
Sieve of Eratosthenes is a simple, ancient algorithm
for finding all prime numbers up to a specified integer.
It was created by Eratosthenes, an ancient Greek mathematician.
*/
function eratosthenes($max) {
$sieve = array_fill(2, ($max-1), false);
while ($key = array_search(false, $sieve)) {
$sieve[$key] = true;
for ($i=$key*$key; $i<=$max; $i+=$key) {
if (array_key_exists($i, $sieve)) {
unset($sieve[$i]);
}
}
}
return array_keys($sieve);
}
?>
piotr dot galas+phpnet at gmail dot com
13-Mar-2007 10:57
Function which converts array to string but not serialize it.
function arraytostring($array)
{
$text.="array(";
$count=count($array);
foreach ($array as $key=>$value)
{
$x++;
if (is_array($value))
{
if(substr($text,-1,1)==')') $text .= ',';
$text.='"'.$key.'"'."=>".arraytostring($value);
continue;
}
$text.="\"$key\"=>\"$value\"";
if ($count!=$x) $text.=",";
}
$text.=")";
if(substr($text, -4, 4)=='),),')$text.='))';
return $text;
}
aflavio at gmail dot com
01-Mar-2007 09:45
/* Correcting me last post */
/**
* Remove a value from a array
* @param string $val
* @param array $arr
* @return array $array_remval
*/
function array_remval($val, &$arr)
{
$array_remval = $arr;
for($x=0;$x<count($array_remval);$x++)
{
$i=array_search($val,$array_remval);
if (is_numeric($i)) {
$array_temp = array_slice($array_remval, 0, $i );
$array_temp2 = array_slice($array_remval, $i+1, count($array_remval)-1 );
$array_remval = array_merge($array_temp, $array_temp2);
}
}
return $array_remval;
}
$stack=Array('apple','banana','pear','apple', 'cherry', 'apple');
array_remval("apple", $stack);
//output: Array('banana','pear', 'cherry')
aflavio at gmail dot com
01-Mar-2007 07:29
/**
* Remove a value from a array
* @param string $val
* @param array $arr
* @return array $array_remval
*/
function array_remval($val, &$arr)
{
$array_remval = $arr;
for($x=0;$x<count($array_remval)-1;$x++)
{
$i=array_search($val,$array_remval);
if($i===false)return false;
$array_remval=array_merge(array_slice($array_remval, 0,$i), array_slice($array_remval, $i+1));
}
return $array_remval;
}
$stack = array("orange", "banana", "apple", "raspberry", "apple");
output $stack = array("orange", "banana", "raspberry");
rune at zedeler dot dk
28-Feb-2007 04:42
Notice that keys are considered equal if they are "=="-equal. That is:
<?
$a = array();
$a[1] = 'this is the first value';
$a[true] = 'this value overrides the first value';
$a['1'] = 'so does this one';
?>
admin \x40 uostas.net
23-Feb-2007 04:09
simple function to remove element from array
saving index sequence
<?php
function array_remval($val,&$arr){
$i=array_search($val,$arr);
if($i===false)return false;
$arr=array_merge(array_slice($arr, 0,$i), array_slice($arr, $i+1));
return true;
}
?>
example:
<?php
$input=Array('a','b','c','d','e');
array_remval('d',$input);
//result:
//Array('a','b','c','e');
?>
christian at enovo dot dk
18-Feb-2007 12:03
function array_flatten(&$a,$pref='',$sep='_') {
$ret=array();
foreach ($a as $i => $j)
{
if (is_array($j)) {
$ret=array_merge($ret, array_flatten($j, $pref . ( strlen($pref) != 0 ? $sep : '' ) . $i ) );
}
else
{
$ret[$pref. $sep . $i] = $j;
}
}
return $ret;
}
Colin
10-Feb-2007 05:31
I couldn't get the previous set pointer functions working for whatever reason so I modifed. I trigger errors if needed but obviously you can do whatever
// setPointer - Sets the pointer to the provided $key in provided $array
final private function setPointer(&$array, $set_key) {
// Check if $array is an array
if (!is_array($array)) {
trigger_error('$array must be an array', E_USER_ERROR);
}
// Check if $key is in $array
if (!array_key_exists($set_key, $array)) {
trigger_error('$set_key must exist in $array', E_USER_ERROR);
}
// Set array pointer to first element
reset($array);
// Cycle through array
while ($set_key != key($array)) {
// Advance the pointer
next($array);
}
}
Try with:
$array = array();
$array[0] = 'zero';
$array[1] = 'one';
$array[2] = 'two';
$array[3] = 'three';
// Set the pointer
setPointer($array, 1);
// Display elements
echo current($array); // Outputs 'one'
echo next($array); // Outputs 'two'
hannes dot dahlberg at gmail dot com
06-Feb-2007 01:12
A small function to get the median of an array filled with numbers
function median($array)
{
sort($array);
return ($array[ceil((count($array) / 2)) - 1] + $array[floor((count($array) / 2))]) / 2;
}
dkrysiak at o2 dot pl
02-Feb-2007 08:40
// note: my previous post have one small error in call to array_key_exists() - posting again - please remove this comment and that note :-)
<?php
/* Another version of subArr() function by simone dot carletti at unimc dot it: */
//{{{ array_select()
/**
* Choose array element with given keys
*
* @param Array $arr
* @param Array $keys Keys/indexes of elements to choose
* @return Array Array with elements being references to the elements od original array with chosen indexes.
*/
function &array_select($arr, $keys)
{
$res = array();
foreach ($keys as $key) {
if (array_key_exists($key, $arr)) {
$res[$key] =& $arr[$key];
}
}
return $res;
} // end: array_select() }}}
/*
In my opinion it should be faster than subArr().
Another difference from subArr() is that elements of returned array are references to the same variables as elements of original array (this can be easily changed)
*/
?>
Mark Lindeman
17-Jan-2007 10:10
Very simple solution for changing the key of an associative array, of course it will fail in a lot of scenarios, but will do the trick in simple arrays:
<?php
function replace_key(&$input, $from_key, $to_key)
{
$input = unserialize(str_replace(':"'.$from_key.'";', ':"'.$to_key.'";',serialize($input)));
}
$array =array("a"=>1, "B"=>2, "c"=>3);
replace_key($array, "B", "b");
print_r($array);
?>
Output:
Array
(
[a] => 1
[b] => 2
[c] => 3
)
php_spam {at] erif dot org
28-Dec-2006 06:52
public domain, yadda yadda. :)
This function takes a flatfile-like array (like the results of a joined query) and normalizes it based on whichever parameters you like.
<?php
function hashByFields($things,$fields) {
$retval=null;
$count = count($fields);
foreach ($things as $thing) {
$fwibble =& $retval;
for ($j=0;$j<$count;$j++) {
$val = $thing[$fields[$j]];
if ($j == $count - 1) {
$fwibble[$val] = $thing;
} else if (!isset($fwibble[$val])) {
$fwibble[$val] = Array();
}
$fwibble =& $fwibble[$val];
}
}
return $retval;
}
?>
filip at mxd dot biz
19-Dec-2006 09:59
a better array_key_set function:
function array_key_set(&$array, $key=0) {
if(is_array($array)) {
if(!array_key_exists($array, $key)) {
return false;
}
reset($array);
while($current = key($array)) {
if($current == $key) {
return true;
}
next($array);
}
}
return false;
}
simone dot carletti at unimc dot it
28-Nov-2006 03:09
Ever wanted to obtain a subset of an associative array from a list of parameters (stored into a non-associative array)?
Give this a try:
<?php
$params = array("name" => "Simone", "gender" => "M", "city" => "Macerata", "phone" => 123);
$fields = array("name", "city");
echo "<pre>";
print_r($params);
print_r($fields);
print_r(subArr($params, $fields));
function subArr($assocArrHaystack, $arrFields)
{
$arrSub = array();
foreach ($assocArrHaystack as $key => $value) {
if (in_array($key, $arrFields)) {
$arrSub[$key] = $value;
}
}
return $arrSub;
}
?>
And the output is:
Array
(
[name] => Simone
[gender] => M
[city] => Macerata
[phone] => 123
)
Array
(
[0] => name
[1] => city
)
Array
(
[name] => Simone
[city] => Macerata
)
Enjoy!
Simone
elkabong at samsalisbury dot co dot uk
13-Nov-2006 11:43
An improvement to the array_deep_copy function I posted ages ago which takes a 'snapshot' of an array, making copies of all actual values referenced... Now it is possible to prevent it traversing the tree forever when an array references itself. You can set the default $maxdepth to anything you like, you should never call this function with the $depth specified!
<?php
/* Make a complete deep copy of an array replacing
references with deep copies until a certain depth is reached
($maxdepth) whereupon references are copied as-is... */
function array_deep_copy (&$array, &$copy, $maxdepth=50, $depth=0) {
if($depth > $maxdepth) { $copy = $array; return; }
if(!is_array($copy)) $copy = array();
foreach($array as $k => &$v) {
if(is_array($v)) { array_deep_copy($v,$copy[$k],$maxdepth,++$depth);
} else {
$copy[$k] = $v;
}
}
}
# call it like this:
array_deep_copy($array_to_be_copied,$deep_copy_of_array,$maxdepth);
?>
Hope someone finds it useful!
zspencer at zacharyspencer dot com
01-Nov-2006 02: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 01: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 12:06
Regarding the string to array (parse_array) function posted by Kevin Law(thanks) and urlencoded by vinaur(thanks) ,
The function will not work correctly if you use integer values as keys.
Thus I exchanged array_merge with a simple combined operator.
For example dealing with 4digit year strings as keys; parse_array(2006:abc,B:bcd) will produce
=> with array_merge:
<?php //...
$result = array_merge($result, parse_line2array(substr($line,$comma_pos+1)));
//...
$result = array_merge($result, parse_line2array($line));
//... ?>
Array (
[0] => abc
[B] => bcd
)
=> with combined operator:
<?php //...
$result += parse_line2array(substr($line,$comma_pos+1));
//...
$result += parse_line2array($line);
//... ?>
Array
(
[2006] => abc
[B] => bcd
)
kthejoker - google mail
20-Sep-2006 05: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 10: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 03: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 12: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 11: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
|