PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links 
search for in the  
previousvirtualarray_change_key_casenext
Last updated: Tue, 09 Jul 2002
view the printer friendly version or the printer friendly version with notes or change language to English | Brazilian Portuguese | Chinese | Czech | Dutch | Finnish | German | Hungarian | Italian | Japanese | Korean | Polish | Romanian | Russian | Spanish | Swedish | Turkish

II. Tableaux

Ces fonctions vous permettent de manipuler et de traiter les tableaux de nombreuses fa�ons. Les tableaux sont tr�s efficaces d�s qu'il s'agit de stocker, g�rer et traiter des donn�es en groupe.

Les tableaux simples et multi-dimensionnels sont support�s et peuvent �tre cr��s par l'utilisateur, ou par une fonction. Il y a des fonctions sp�cifiques qui remplissent des tableaux � partir de r�sultats de requ�tes, et de nombreuses fonctions retournent un tableau.

Voir aussi is_array(), explode(), implode(), split() et join().

Table des mati�res
array_change_key_case --  Retourne un tableau dont toutes les cl�s ont �t� forc�es en majuscules ou minuscules.
array_chunk -- S�pare un tableau en tableaux de taille inf�rieure
array_count_values -- Compte le nombre de valeurs dans un tableau
array_diff -- Calcule la diff�rence entre deux tableaux
array_fill -- Remplis un tableau avec une m�me valeur
array_filter -- Filtre les �l�ments d'un tableau
array_flip --  Remplace les cl�s par les valeurs, et les valeurs par les cl�s
array_intersect -- Calcule l'intersection de tableaux
array_key_exists -- Checks if the given key or index exists in the array
array_keys -- Retourne toutes les cl�s d'un tableau
array_map -- Applique sur fonction sur des tableaux
array_merge_recursive -- Combine plusieurs tableaux ensembles, r�cursivement
array_merge -- Rassemble plusieurs tableaux
array_multisort -- Tri multi-dimensionnel
array_pad --  Compl�te un tableau jusqu'� la longueur sp�cifi�e, avec une valeur.
array_pop --  D�pile un �l�ment de la fin d'un tableau
array_push --  Empile un ou plusieurs �l�ments � la fin d'un tableau
array_rand --  Prend une ou plusieurs valeurs, au hasard dans un tableau
array_reduce --  R�duit it�rativement un tableau
array_reverse --  Renverse l'ordre des �l�ments d'un tableau
array_search --  Recherche dans un tableau la cl� associ�e � une valeur
array_shift --  D�pile un �l�ment au d�but d'un tableau
array_slice -- Extrait une portion de tableau
array_splice --  Efface et remplace une portion de tableau
array_sum --  Calcule la somme des valeurs du tableau
array_unique -- D�doublonne un tableau
array_unshift --  Empile un ou plusieurs �l�ments au d�but d'un tableau
array_values -- Retourne les valeurs d'un tableau
array_walk --  Ex�cute une fonction sur chacun des membres d'un tableau.
array --  Cr�e un tableau
arsort --  Trie un tableau en ordre inverse
asort -- Trie un tableau en ordre
compact --  Cr�e un tableau contenant les variables et leur valeur
count -- Compte le nombre d'�l�ments d'un tableau
current -- Transforme une variable en tableau
each --  Retourne chaque paire cl�/valeur d'un tableau
end --  Positionne le pointeur de tableau en fin de tableau
extract --  Importe les variables dans la table des symboles
in_array --  Indique si une valeur appartient � un tableau
key -- Retourne une cl� d'un tableau associatif
krsort --  Trie un tableau en sens inverse et suivant les cl�s
ksort -- Trie un tableau suivant les cl�s
list --  Transforme une liste de variables en tableau
natcasesort --  Tri d'un tableau avec l'algorithme � "ordre naturel" insensible � la casse
natsort --  Tri d'un tableau avec l'algorithme � "ordre naturel"
next --  Avance le pointeur interne d'un tableau
pos -- Retourne l'�l�ment courant d'un tableau
prev -- Recule le pointeur courant de tableau
range --  Cr�e un tableau contenant un intervalle d'�l�ments
reset --  Remet le pointeur interne de tableau au d�but
rsort -- Trie en ordre inverse
shuffle -- M�lange les �l�ments d'un tableau
sizeof -- Retourne le nombre d'�l�ment d'un tableau
sort -- Trie le tableau
uasort --  Trie d'un tableau en utilisant une fonction de comparaison d�finie par l'utilisateur.
uksort --  Trie un tableau par ses cl�s en utilisant une fonction de comparaison d�finie par l'utilisateur
usort --  Trie un tableau en utilisant une fonction de comparaison d�finie par l'utilisateur
User Contributed Notes
Tableaux
add a note about notes
[email protected]
01-Feb-1999 12:30

use the max function to get the highest value of an array e.g:
$maxval = max($array);

[email protected]
04-Apr-2001 09:58

I added this note to array_pop, but it's probably more applicable here:

If you use array_pop, the numeric indices will be renumbered if there are any gaps. So if you start with

$a[5]="five";
$a[6]="six";

and then do array_pop($a), you now have $a[0]="five", not $a[5]="five", as you might expect. In other words, $a does not necessarily equal array_pop(array_push($a, 1)).

Response in the bug database was the following:

--
Presently, all splice-derived functions reorder numeric keys. There's not much to do about it, since it's the way Zend Engine handles numeric hash keys. Changing it either way won't bring more consistent functionality, so in the meantime it is just as it is.
--

I'd disagree that changing my array indices is consistent, but there you are. I don't know which array functions are splice-derived, so look out for this.

[email protected]
29-Aug-2001 07:58

You should really read , there is a lot of info there about how to handle arrays, how to check wether indices are set, how to modify an array, anything.
[email protected]
29-Jan-2002 09:55

You should pay attention to the fact that some functions act directly on the array (such as asort) and some don't touch the array but return a copy (such as array_reverse). If you use one in the improper context you won't get a warning. It took me a while to notice this as I do a lot of coding by memory and don't refer to the function documentation unless I need to.
[email protected]
05-Feb-2002 05:56

To display the value of a variable from a two dimentional array inside a quoted string, use the following syntax:

<?php

$var = array(
'name' => array(
'first' => 'Caleb',
'last' => 'Maclennan'
)
);

echo "My first name is {$var[name][first]}!";

?>

[email protected]
14-Apr-2002 09:34

Looping through an array, and printing each item:

for ($i = 0; $i < count($array_name); $i++) { echo("$i - $arrayname[$i]"); }

[email protected]
20-Apr-2002 12:43

You should pay attention to the fact that some functions act directly on
the array (such as asort) and some don't touch the array but return a copy
(such as array_reverse).

Tim Burly

[email protected]
13-May-2002 07:12

I bet there was someone else that needed to translate an associative array from php into, lets say, an associative array in JavaScript (or other programing language)
You can use these functions i wrote, which i tried to be as customizable as possible, for use in many other languages.

For example, in JavaScript an associative array would look like:

array: {
category1: {
title: 'cat title 1',
name: 'cat_name_1',
desc: 'cat desc 1'
},
category2: {
title: 'cat title 2',
name: 'cat_name_2',
desc: 'cat desc 2'
},
property: value
}

Here are the functions i wrote: (legend at the end)

function ga($arr, $sep, $grp, $elemsep, $end, $ind, $indpos) {
$newarr = "";
foreach( $arr as $key=>$val ) {

if( is_array( $val ) ) {

$newarr .= str_repeat( $ind, $indpos ).$key.$sep.$grp[0].$end;
$newarr .= ga( $val, $sep, $grp, $elemsep, $end, $ind, $indpos + 1 );
$newarr .= str_repeat( $ind, $indpos ).$grp[1];
}
else
$newarr .= str_repeat( $ind, $indpos ).$key.$sep.$val;

$newarr .= ( ( $arr[$key] == end( $arr ) ) ? "" : $elemsep ) . $end;
}

return $newarr;
}

function genarr( $arrname, $genfunc, $sep = ": ", $grp = array( "{", "}" ) , $elemsep = ",", $end = "\n", $ind = "\t", $indpos = 1 ) {
global $$arrname;
return $arrname.$sep.$grp[0].$end.$genfunc ($$arrname, $sep, $grp, $elemsep, $end, $ind, $indpos).$grp[1];
}

Legend:

$arr = the php associative array to transform

$sep = the separator char/string between the key and the value (in JavaScript its ":", in PHP its "=>")

$grp = an array having the 1st element as the "new array" character and the 2nd element as the "array end" character (in javaScript they are "{" and "}", in PHP they are "array(" and ")" )

$elemsep = elements separator (in javascript and PHP its "," )

$end = the caracter appended at the end of an element

$ind = indentation character

$indpos = default indent

NOTE: if you would like an inline output, then set the $end = "" and the $ind = "".
If you want a stylish output you can set the $end = "\n" and $ind = "\t".

$genfunc = a STRING evaluating to the the fetching function name (in this case "ga")

$arrname = a STRING, evaluating to the array variable name (note the calling to it by "$$arrname" )

NOTE: for JavaScript, i set all arguments by default in the "genarr" function.

EXAMPLE:

Supposing you have a PHP associative array:

$bob = array(
"key1" => array (
......

then for javaScript, you should call the "genarr" function like this:

$JSArray = genarr( "bob", "ga" )

note the arguments: "bob" and "ga"

This will result in a Javascript array like this:

bob: {
key1: {
.....

Hope it helped because i need to have a huge JavaScript associative array for one of the sites i run but also the same array in PHP and its a hell of a job updating 2 pieces of code when PHP can generate it dynamically, thus its sufficient to make changes only in the PHP code.

Cheers

P.S. let me know if you found it useful

[email protected]
13-May-2002 10:51

In the last post i missed something in the fetching function. It had troubles handling boolean values and i forgot strings as well. Also, detecting the end of a sub-array didnt work as expected. Here are the new versions that worked with everything i threw at it:

function ga($arr, $sep, $grp, $elemsep, $str, $end, $ind, $indpos) {

$newarr = "";
$len = count( $arr );
for( $i=0; $i<$len; $i++ ) {

//get current key,value pair
list( $key, $val ) = each( $arr );

if( is_array( $val ) ) {
//calling recursively if it hits a sub-array
$newarr .= str_repeat( $ind, $indpos ).$key.$sep.$grp[0].$end;
$newarr .= ga( $val, $sep, $grp, $elemsep, $str, $end, $ind, $indpos + 1 );
$newarr .= str_repeat( $ind, $indpos ).$grp[1];
}
else {
$newarr .= str_repeat( $ind, $indpos ).$key.$sep;
//determine element type
$newarr .= ( is_bool( $val ) ) ? (($val) ? 'true' : 'false') : ( is_string( $val ) ? $str.addslashes( $val ).$str : $val );
}

//if last element then don't add $elemsep after it
$newarr .= ( $i == $len-1 ) ? $end : $elemsep.$end;
}

return $newarr;
}


function genarr( $arrname, $genfunc, $sep = ': ', $grp = array( '{', '}' ) , $elemsep = ',', $str = '"', $end = "\r\n", $ind = "\t", $indpos = 1 ) {
global $$arrname;
return $arrname.$sep.$grp[0].$end.$genfunc ($$arrname, $sep, $grp, $elemsep, $str, $end, $ind, $indpos).$grp[1];
}

I also added addslashes() to string values. There is a new argument:

$str = the string delimiter (usually " \" " or " \' " ). The second function only has the new argument modified. The rest is the same.

Please let me know if you find anything going wrong.

Cheers

[email protected]
28-May-2002 04:10

here's a little function i wrote to convert any multidimensional array to an xml tree. it has this prototype:

string arr2xml (array array, [string tree_name])

if they are associative arrays, the element keys will be used as node names. any numeric arrays will be filled in with level1, level2 .. if you omit the second (optional) argument, it uses level0 as the top of the tree.

function arr2xml ($arr)
{
if (func_num_args () < 3)
{
$wrapper = (func_num_args < 2) ? array ($arr) : array (func_get_arg(1)=>$arr);
$xml = arr2xml ($wrapper, '', 0);
}
else
{
$level = func_get_arg (2);
while (list ($key, $val) = each ($arr))
{
if ($key === (int)$key) $key = 'level'.$level;
$xml .= '<'.$key.'>';
if (gettype ($val) == 'array')
{
$xml .= arr2xml ($val, '', $level+1);
}
else
{
$xml .= $val;
}
$xml .= '</'.$key.'>';
}
}
return $xml;
}

[email protected]
29-May-2002 02:17

could an admin please remove my last post? this is a much better rewrite of the arr2xml () function.

its more sensibly written and flexible now. theres only one required argument, the array itself. it has this prototype:

string arr2xml (array array, [string tree_name], [[int level])

use the second argument if you want to specify a name for the top of the tree - otherwise it defaults to level0. the first call to the function is kind of a dummy top level that wraps the array inside another array and calls the function for real.

dont use the third argument. thats used to keep track of the levels in all the recursive calls.

heres the code:

function arr2xml ($arr)
{
if (func_num_args () < 3)
{
$wrapper = (func_num_args < 2) ? array ($arr) : array (func_get_arg(1)=>$arr);
$xml = arr2xml ($wrapper, '', 0);
}
else
{
$level = func_get_arg (2);
while (list ($key, $val) = each ($arr))
{
if ($key === (int)$key) $key = 'level'.$level;
$xml .= '<'.$key.'>';
if (gettype ($val) == 'array')
{
$xml .= arr2xml ($val, '', $level+1);
}
else
{
$xml .= $val;
}
$xml .= '</'.$key.'>';
}
}
return $xml;
}

bishop
07-Jun-2002 05:42

Sometimes you need an array that has all keys exactly equal to all values. For example, arrays that look like:
array('a' => 'a', 'b' => 'b', 'c' => 'c');

You can either do it manually (a pain for count($a) > 2), or use array_smear():

/* smear values across into keys, or vice-versa */
function array_smear($a, $v2k = true) {
$values = ($v2k) ? array_values($a) : array_keys($a);

$a = array();
foreach ($values as $v)
$a[$v] = $v;

return ($a);
}

array_smear takes an array, then a boolean specifying whether you want to smear the values over into the keys (the default, and probably what you usually want) or vice-versa.

So:
$a = array('a', 'b', 'c');

$x = array_smear($a);
// x == array('a' => 'a', 'b' => 'b', 'c' => 'c');

$y = array_smear($a, false);
// y == array(0 => 0, 1 => 1, 2 => 2);

[email protected]
13-Jun-2002 09:13

I am working on a project wherein I had to delete something from an array, but I couldn't leave a hole in the array.
For example:
<?php
$myarray[0] = "test0";
$myarray[1] = "test1";
$myarray[2] = "test2";

unset($myarray[1]);
for($i=0;$i<count($myarray);$i++) {
echo $i." = ".$myarray[$i]."
";
}

/*
Outputs this:

0 = test0
1 =

*/
?>
Obviously, that doesn't work. ;) I won't explain why, but you can probably figure that out yourself.
Anyway, I wrote a function to correct this problem:

<?php

function deleteandpush($array, $indice) {

unset($array[$indice]);

for($i=0;$i<count($array);$i++) {

if(!isset($array[$i])) { $array[$i] = $array[$i+1]; unset($array[$i+1]); };

}

return $array;
}

$myarray[0] = "test0";
$myarray[1] = "test1";
$myarray[2] = "test2";
$myarray[3] = "test3";
$myarray[4] = "test4";

$array = deleteandpush($myarray, 3);

for($i=0;$i<count($array);$i++) {
echo $i.":".$array[$i]."
";
}

/*

Outputs:
0:test0
1:test1
2:test2
3:test4

*/

?>
Hope this helps someone.

spam (at) speedcapture . com
15-Jun-2002 01:50

I want to share a VERY usefull way to debug php and arrays:

just create a file like array.func.inc.php

paste the following code into the file.

// To make ANY array visible ...

function viewArray($arr)
{
echo '<table cellpadding="0" cellspacing="0" border="1">';
foreach ($arr as $key1 => $elem1) {
echo '<tr>';
echo '<td>'.$key1.'&nbsp;</td>';
if (is_array($elem1)) { extArray($elem1); }
else { echo '<td>'.$elem1.'&nbsp;</td>'; }
echo '</tr>';
}
echo '</table>';
}

function extArray($arr)
{
echo '<td>';
echo '<table cellpadding="0" cellspacing="0" border="1">';
foreach ($arr as $key => $elem) {
echo '<tr>';
echo '<td>'.$key.'&nbsp;</td>';
if (is_array($elem)) { extArray($elem); }
else { echo '<td>'.htmlspecialchars($elem).'&nbsp;</td>'; }
echo '</tr>';
}
echo '</table>';
echo '</td>';
}

close the file and include that file into any other php document. If u want to check the content of an array just type viewarray($array);

webkid%webkid.com
19-Jun-2002 05:47

A painstakenly written function to add a "value" to a recursive array using a pathlist (also in the format of an array):

function recurse($a,$rm,$k,$d){ if (sizeof($rm)==0){$a[$k]=$d;
return ($a);}
$sh=array_shift($rm); $a[$sh]=recurse ($a[$sh],$rm,$k,$d);
return ($a);}

Called like this: $ary=recurse($ary, array("level1","level2","level3"),"key",$value);

So an array like
Array(
[0] => a
[1] => b
[2] => c
[d] => Array
( [0] => a
[1] => b
[c] => Array
( [0] => e
[1] => f
[2] => g
[3] => h
[i] => Array
( [0] => n
) ) ) )
Can become
Array(
[0] => a
[1] => b
[2] => c
[d] => Array
( [0] => a
[1] => b
[c] => Array
( [0] => e
[1] => f
[2] => g
[3] => h
[i] => Array
( [0] => n
[key] => data
) ) ) )
With the call
$ary=recurse($ary,array("d","c","i"),"key","data");

[email protected]
21-Jun-2002 05:14

<?

$myarray = array();

$myarray[1] = 1;
$myarray[2] = 2;
$myarray[3] = 3;
$myarray[4] = 4;

// I want to move $myarray[2] to the 4th position.

$ordered_array = reposition($myarray, 2,4);

foreach($ordered_array as $key=>$value){
echo "ordered_array[$key] = $value";
}

?>

// The output of this function will be:

ordered_array[1] = 1
ordered_array[2] = 4
ordered_array[3] = 2
ordered_array[4] = 3

<?

function reposition($myarray,$myarray_key,$newpos){

$oldpos = $myarray[$myarray_key];

foreach($myarray as $key=>$value){
if($key==$myarray_key){
$myarray[$key] = $newpos;
}else{

if($oldpos>=$newpos){ // It's moving up the array

// Values following it will go down (lower position)

if($myarray[$key]<=$oldpos && $myarray[$key]>=$newpos){
$myarray[$key]++;
}

}else{ // It's moving down the array

// Values preceding it will go up (higher position)

if($myarray[$key]>=$oldpos && $myarray[$key]<=$newpos){
$myarray[$key]--;
}
}
}
}
return $myarray;
}

?>

[email protected]
07-Jul-2002 09:19

i have a problem and i'm hoping somebody could help me with it.
basically i have a form with multiple text input boxes.

the number of these increases...so the next <tr> would have username2,comment2,date2,time2.And the nextone 3...and so on.

So when the data is posted it s saved as an array in $HTTP_POST_VARS.
what i would need to do is somehow create a function that would foreach usernameX commentX dateX timeX do a mysql query:
UPDATE comments SET username='$username', comment='$comment', date='$date', time='$time' where id=$key"
.
This way all of the fields would be updated with one post.oh yeah $id is the X at the end of username,comment,date and time.
The only way i knew how to do it(since i know almost zero php.
1)
do a listing of the $HTTP_POST_VARS.
2)remove all instances of username comment date and time from the keys.and there for get a listing
1
1
1
1
2
2
2
2
...
then just check if the key wasn't allready done and if it wasn't extract the username+key comment+key date+key and time+key values of of
$HTTP_POST_VARS, and update the database.
Basically i got everything out of the array so i can just get the X values and call the array again.
Seems sort of stupid and a waste of time.
I'm 100% sure there is an easier way of doing it.With foreach or smth.But everything i tried failed =).
anyone have any ideas what to do?
here is the so called code(well only the part that i think can be done another way:
and yes the crap actually works:

this is the part of the code that basically does all the garbage i wrote above:

while (list($key, $value) = each ($HTTP_POST_VARS)) {

$search = "/comment/";
$replacement = "";
$key = preg_replace($search, $replacement, $key);
$search = "/username/";
$replacement = "";
$key = preg_replace($search, $replacement, $key);
$search = "/date/";
$replacement = "";
$key = preg_replace($search, $replacement, $key);
$search = "/time/";
$replacement = "";
$key = preg_replace($search, $replacement, $key);

if($key!=$prev_key) {
if($key != "function" AND $key != "show") {
global $HTTP_POST_VARS;
$username = "username";
$username .= $key;
$comment = "comment";
$comment .= $key;
$date = "date";
$date .= $key;
$time = "time";
$time .= $key;
$username = $HTTP_POST_VARS["$username"];
$comment = $HTTP_POST_VARS["$comment"];
$date = $HTTP_POST_VARS["$date"];
$time = $HTTP_POST_VARS["$time"];

$query = ("UPDATE comments SET username='$username', comment='$comment', date='$date', time='$time' where id=$key");

$result = MYSQL_QUERY($query);
}
}
$prev_key = $key;

}

MYSQL_CLOSE();

does anybody have an example of a code that can edit multiple rows and columns at once?...like phpmyadmin.

[email protected]
29-Jul-2002 12:31

CSS-Parsing Function with associative array and PREG - splitting.
You can fetch CSS-Tags with

$aCSS=parseCSS("style.css");
echo $aCSS["body"]["background-color"];

function parseCSS($filename)
{
$fp=fopen($filename,"r");
$css = fread($fp, filesize ($filename));
fclose($fp);

$css=preg_replace("/[\s,]+/","",$css);
$css_class = preg_split("/}/", $css);

while (list($key,$val) = each ($css_class))
{
$aCSSObj=preg_split("/{/",$val);
$a=preg_split("/;/",$aCSSObj[1]);
while(list($key,$val0) = each ($a))
{
if($val0 !='')
{
$aCSSSub=preg_split("/:/",$val0);
$aCSSItem[$aCSSSub[0]]=$aCSSSub[1];
}
}
$aCSS[$aCSSObj[0]]=$aCSSItem;
unset($aCSSItem);
}

unset($css);
unset($css_class);
unset($aCSSSub);
unset($aCSSItem);
unset($aCSSObj);

return $aCSS;
}

[email protected]
23-Aug-2002 09:56

Here is my var2xml function.
This one will convert any var type except objects, and for arrays it will take indexed subarrays and assume they should be duplicates of the parent tag name.

function var2xml ($name, $value, $indent = 1)
{
$indentstring = $this->indentstring;
for ($i = 0; $i < $indent; $i++)
{
$indentstring .= $this->indentstring;
}
if (!is_array($value))
{
$xml = $indentstring.'<'.$name.'>'.$value.'</'.$name.'>'."\n";
}
else
{
if($indent === 1)
{
$isindex = False;
}
else
{
$isindex = True;
while (list ($idxkey, $idxval) = each ($value))
{
if ($idxkey !== (int)$idxkey)
{
$isindex = False;
}
}
}

reset($value);
while (list ($key, $val) = each ($value))
{
if($indent === 1)
{
$keyname = $name;
$nextkey = $key;
}
elseif($isindex)
{
$keyname = $name;
$nextkey = $name;
}
else
{
$keyname = $key;
$nextkey = $key;
}

if (is_array($val))
{
$xml .= $indentstring.'<'.$keyname.'>'."\n";
$xml .= $this->var2xml ($nextkey, $val, $indent+1);
$xml .= $indentstring.'</'.$keyname.'>'."\n";
}
else
{
$xml .= $this->var2xml ($nextkey, $val, $indent);
}
}
}
return $xml;
}

add a note about notes
previousvirtualarray_change_key_casenext
Last updated: Tue, 09 Jul 2002
show source | credits | stats | mirror sites
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Sat Aug 31 06:19:44 2002 CEST