Regarding cyberchrist at futura dot net's function. It makes an unnecessary array_merge(); the elements of $b that are merged with those of $a are immediately removed again by the array_diff(). The "limiting to known values" is entirely unnecessary, in other words: arrays already only contain "known values".
Also, the description and function only address the issue of whether $a is a subset of $b, not whether it is a proper subset. For $a to be a proper subset of $b, it must also be the case that $b is not a subset of $a.
Taking those points into account (and a personal aesthetic dislike of "if(test) return true; else return false;" gives:
<?php
function is_subset($a, $b)
{
return count(array_diff($a,$b))==0;
}
function is_proper_subset($a, $b)
{
return is_subset($a, $b) && !is_subset($b, $a);
}
?>
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() 函数中,使其降序排列。
排序类型标识:用于各种排序函数
参见
参见 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_keys — Fill an array with values, specifying keys
- 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 — 使用用户自定义的比较函数对数组中的值进行排序
User Contributed Notes
Array 数组函数
Hayley Watson
17-Oct-2007 07:10
17-Oct-2007 07:10
Hayley Watson
17-Oct-2007 11:40
17-Oct-2007 11:40
Yet Another Yet Another reimplementation. This one finds the maximum array nesting a la the post by ob at babcom dot biz, boesn't generate "Undefined variable" notices.
<?php
function maximum_array_depth($array)
{
if(!is_array($array)) return 0;
return 1+max(array_map('maximum_array_depth', $array));
}
$t1 = array(0,1,2,array(3,4),5,array(array(6),array(7,8),9));
echo maximum_array_depth($t1);
?>
Hayley Watson
17-Oct-2007 11:26
17-Oct-2007 11:26
Yet Another flatten-multidimensional-array function. For numerically-indexed arrays.
<?php
function flatten_array($array)
{
if(!is_array($array)) return array($array);
return call_user_func_array('array_merge', array_map('flatten_array', $array));
}
?>
$t1 = array(0,1,2,array(3,4),5,array(array(6),array(7,8),9));
print_r(flatten_array($t1));
?>
cyberchrist at futura dot net
15-Oct-2007 09:33
15-Oct-2007 09:33
Lately, dealing with databases, I've been finding myself needing to know if one array, $a, is a proper subset of $b.
Mathematically, this is asking (in set theory) [excuse the use of u and n instead of proper Unicode):
( A u B ) n ( ~ B )
What this does is it first limits to known values, then looks for anything outside of B but in the union of A and B (which would be those things in A which are not also in B).
If any value exists in this set, then A is NOT a proper subset of B, because a value exists in A but not in B. For A to be a proper subset, all values in A must be in B.
I'm sure this could easily be done any number of ways but this seems to work for me. It's not got a lot of error detection such as sterilizing inputs or checking input types.
// bool array_subset( array, array )
// Returns true if $a is a proper subset of $b, returns false otherwise.
function array_subset( $a, $b )
{
if( count( array_diff( array_merge($a,$b), $b)) == 0 )
return true;
else
return false;
}
James Churchman
16-Sep-2007 04:28
16-Sep-2007 04:28
very simple tip.. if you want an array's keys.. but not the values in it then this will do the trick
$keys_only_array = array_flip(array_keys($origional_array_with_keys_and_values));
james
tvscoundrel at hotmail dot com
05-Sep-2007 05:52
05-Sep-2007 05:52
phamphong_tn's function to remove an element from an array seems a bit complicated for something that is actually quite simple.
Here's another way to remove an element from an array:
<?php
//the function
function removeArrayElement(&$arr, $index){
if(isset($arr[$index])){
array_splice($arr, $index, 1);
}
}
//testing the function
$test = array("zero", "one", "two", "three");
echo "<pre>";
print_r($test);
echo "</pre>";
$this->removeArrayElement($test, 2);
echo "<pre>";
print_r($test);
echo "</pre>";
?>
output:
Array
(
[0] => zero
[1] => one
[2] => two
[3] => three
)
Array
(
[0] => zero
[1] => one
[2] => three
)
To remove an element from an associative array is even simpler:
unset($arr[$index]);
Kazuyoshi Tlacaelel
30-Aug-2007 02:56
30-Aug-2007 02:56
<?php
/**
* converts a multidimensional array to a flat array
*
* trying to keep the original names of the keys
* if repeated keys are found a hash will be added to the
* keys trying to keep as much as possible of the original
* key context
*
* september 30 2007
*
* PHP version 5
*
* @license GPL
*
*/
$array = array ( 0 => array ( 0 => 1, 1 => 2, 2 => array ( 0 => 3, 1 => 4, 2 =>
array ( 0 => 5, 1 => 6, 2 => array ( 0 => 7, 1 => 8,),),), 3 => array (
0 => array ( 0 => 9, 1 => 10, 2 => array ( 0 => 11, 1 => 12,
2 => array ( 0 => 13, 1 => 14, 2 => array ( 0 => 15, 1 => 16,),),),),
1 => array ( 0 => 17, 1 => 18,),),), 1 => array ( 0 => 19, 1 => 20,),
2 => array ( 0 => array ( 0 => 21, 1 => 22, 2 => array ( 0 => 23, 1 => 24,
2 => array ( 0 => 25, 1 => 26, 2 => array ( 0 => 27, 1 => 28,),),),),
1 => array ( 0 => 29, 1 => 30,),),);
/**
* transforms a multidimensional array to a flat array
*
* the parameter is referenced
* so no returning value is needed
* @param array $array the multidimensional array to flat
* @return void
*/
function array_flatten(&$array)
{
function has_arrays($array)
{
foreach ($array as $item) {
if (is_array($item)) {
return true;
}
}
return false;
}
function copy_array(&$array, $array_key)
{
$array2 = $array[$array_key];
unset($array[$array_key]);
foreach ($array2 as $subkey => $subvalue) {
if (array_key_exists($subkey, $array)) {
$array[generate_unique_key($subkey)] = $subvalue;
} else {
$array[$subkey] = $subvalue;
}
}
}
function generate_unique_key($key)
{
if (strlen($key)>8) {
$key = $key[0] . $key[1] . $key[2];
}
$id = $key . '_';
$uid = uniqid();
$len = strlen($uid);
$max = (9 - strlen($key));
for ($c = $len; ; $c --) {
$id .= $uid[$c];
if ($c == ($len - $max)) {
break;
}
}
return $id;
}
function get_array_indexes($array)
{
$ret_array = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$ret_array[] = $key;
}
}
return $ret_array;
}
while(has_arrays($array)) {
foreach (get_array_indexes($array) as $key) {
copy_array($array, $key);
}
}
}
array_flatten($array);
array_multisort($array);
var_export($array);
/**
* OUTPUT
*
* array (
* 0 => 1,
* '1_403767b6' => 2,
* '0_793767b6' => 3,
* '1_8a3767b6' => 4,
* '0_454767b6' => 5,
* '1_564767b6' => 6,
* '0_035767b6' => 7,
* '1_345767b6' => 8,
* '0_e74767b6' => 9,
* '1_f84767b6' => 10,
* '0_855767b6' => 11,
* '1_a65767b6' => 12,
* '0_4e5767b6' => 13,
* '1_6f5767b6' => 14,
* '0_566767b6' => 15,
* '1_876767b6' => 16,
* '0_5b4767b6' => 17,
* '1_6c4767b6' => 18,
* '0_d43767b6' => 19,
* 1 => 20,
* '0_4e3767b6' => 21,
* '1_5f3767b6' => 22,
* '0_ad4767b6' => 23,
* '1_ce4767b6' => 24,
* '0_485767b6' => 25,
* '1_695767b6' => 26,
* '0_116767b6' => 27,
* '1_426767b6' => 28,
* '0_814767b6' => 29,
* '1_924767b6' => 30,
* )
*/
?>
pedja at uzice dot net
07-Aug-2007 08:38
07-Aug-2007 08: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 02:27
31-Jul-2007 02: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 05:16
19-Jul-2007 05: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 10:20
19-Jul-2007 10: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
29-Jun-2007 07:34
29-Jun-2007 07:34
This is a code remove an other row of array
<?php
//$mang is an array, $id is index of row in array
function remove($mang,$id)
{
$flag = false;
$count = count($mang);
$i = 0;
while ($flag!=true && $i<$count) {
if ($i==$id) {
unset($mang[$i]);
$flag = true;
$index = $i;
}
else {
if ($temp) {
array_push($temp,$mang[$i]);
}
else
{
$temp = array($mang[$i]);
}
}
$i++;
}
if ($flag) {
while ($index<$count)
{
if ($temp) {
array_push($temp,$mang[$index+1]);
}
else
{
$temp = array($mang[$index+1]);
}
$index++;
}
}
array_pop($temp);
return $temp;
}
$arr = array(array("id"=>"1","name"=>"b"),array("id"=>"2","name"=>"d"));
array_push($arr,array("id"=>"3","name"=>"f"));
array_push($arr,array("id"=>4,"name"=>"g"));
$arr = remove($arr,2);
echo "<pre>";
print_r($arr);
?>
peanutpad at msn dot com
16-Jun-2007 06:15
16-Jun-2007 06: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
12-Jun-2007 12:06
12-Jun-2007 12:06
Bugs happen, but how can people post functions that WON'T EVEN COMPILE! I truly detest finding a cool code snippet or function and then having to debug them. Sorry for the rant, but I have experienced this scenario a number of times. TEST YOUR CODE, THEN POST!
Here is a revised and corrected previously posted function ArrayDepth, which had 3 bugs and yes, would not compile.
function ArrayDepth($Array,$DepthCount=-1) {
// Find maximum depth of an array
// Usage: int ArrayDepth( array $array )
// returns integer with max depth
// if Array is a string or an empty array it will return 0
$DepthArray=array(0);
$DepthCount++;
$Depth = 0;
if (is_array($Array))
foreach ($Array as $Key => $Value) {
$DepthArray[]=ArrayDepth($Value,$DepthCount);
}
else
return $DepthCount;
return max($DepthCount,max($DepthArray));
}
sean at aliencreations dot com
10-Jun-2007 07:36
10-Jun-2007 07: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
30-May-2007 05:57
30-May-2007 05: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
17-May-2007 05:05
17-May-2007 05: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 10:14
26-Apr-2007 10: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 09:34
23-Apr-2007 09: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
18-Apr-2007 04:13
18-Apr-2007 04: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 11:12
17-Apr-2007 11: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 05:41
05-Apr-2007 05: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 08:49
19-Mar-2007 08: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 11:18
14-Mar-2007 11: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
14-Mar-2007 06:57
14-Mar-2007 06: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
02-Mar-2007 05:45
02-Mar-2007 05: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 03:29
01-Mar-2007 03: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 12:42
28-Feb-2007 12: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 12:09
23-Feb-2007 12: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 08:03
18-Feb-2007 08: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 01:31
10-Feb-2007 01: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 09:12
06-Feb-2007 09: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 04:40
02-Feb-2007 04: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
