|
|
II. Array Functies
Deze functies maken het gebruik en de manipulatie van arrays
mogelijk op verschillende manieren. Arrays zijn essentieel
voor het bewaren en beheren van sets van variabelen.
Simpele en multi-dimensionelale arrays worden ondersteund, en
kunnen door gebruikers of een andere functie worden gemaakt.
Er zijn specifieke database handling functies die arrays
invullen aan de hand van database queries, en verschillende
functies geven arrays terug.
Je kunt de Arrays
sectie van de manual bekijken voor een gedetailleerde uitleg over
hoe arrays worden geimplementeerd en gebruikt in PHP.
AfhankelijkhedenDeze functies zijn beschikbaar als onderdeel van
de standarad module die altijd beschikbaar is. InstallatieDeze extensie gebruikt geen configuratie regels. Configuratie tijdens scriptuitvoerDeze extensie gebruikt geen configuratie regels. Resource typesDeze extensie maakt geen gebruik van resources. Voorgedefineerde constanten
De constanten die hier staan zijn altijd aanwezig als een onderdeel van de PHP kern.
Sorteervolgorde:
Sorteertypen: gebruikt door diverse sorteerfuncties
- SORT_REGULAR
(integer)
SORT_REGULAR wordt normaal gebruikt om items te
vergelijken.
- SORT_NUMERIC
(integer)
SORT_NUMERIC wordt gebruikt om items numeriek te
vergelijken.
- SORT_STRING
(integer)
SORT_STRING wordt gebruikt om items als strings
te vergelijken.
- Inhoudsopgave
- array_change_key_case -- Geeft een array terug met alle string keys aks kiwercase
of als uppercase
- array_chunk -- Verdeel een array in stukken
- array_count_values -- Telt alle waarden in een array
- array_diff_assoc -- Berekent het verschil tussen arrays met een toegevoegde index check
- array_diff -- Berekent het verschil tussen arrays
- array_fill -- Vul een array met waarden
- array_filter --
Filtert elementen van een array via een callback functie
- array_flip -- Verwisselt alle keys met de geassocieerde waarden in een array
- array_intersect_assoc -- Berekent de intersectie van arrays met een extra index check
- array_intersect -- Berekent de intersectie van arrays
- array_key_exists -- Kijkt of de gegeven key of index bestaat in de array
- array_keys -- Geeft alle keys van een array terug
- array_map --
Past de callback functie toe op de elementen van de gegeven arrays
- array_merge_recursive -- Voeg twee arrays recursief samen
- array_merge -- Voeg twee of meer arrays samen
- array_multisort -- Sorteer meerdere of multi-dimensionale arrays
- array_pad --
Vul een array aan tot de gegeven lengte met een waarde
- array_pop -- Haal een element van het einde van een array af
- array_push --
Voeg een of meer elementen toe aan het einde van een array
- array_rand --
Kies een of meer willekeurige waarden uit een array
- array_reduce --
Reduceer de array iteratief tot een enkele waarde via een
callback functie
- array_reverse --
Geef een array terug met elementen in omgekeerde volgorde
- array_search --
Zoekt in de array naar een gegeven waarde en geeft de
corresponderende key terug bij succes
- array_shift --
Schuif een element van het begin van de array af
- array_slice -- Haal een plak uit de array
- array_splice --
Verwijder een gedeelte van de array en vervang dat door
iets anders
- array_sum --
Bereken de som van de waarden in een array
- array_unique -- Verwijdert dubbele waarden uit een array
- array_unshift --
Voeg een of meer elementen toe aan het begin van een array
- array_values -- Geeft alle waarden van een array terug
- array_walk --
Pas een gebruikersfunctie toe op elk element van een array
- array --
Maak een array
- arsort --
Sorteer een array in omgekeerde volgorde en bewaar index associatie
- asort -- Sorteer een array en bewaar de index associatie
- compact --
Maak een array met daarin variabelen en hun waarden
- count -- Telt de elementen in een array
- current -- Geeft het huidige element in een array terug
- each --
Geef het huidige key-waarde paar terug uit een array en
verplaats de array cursor een stap naar voren
- end --
Zet de interne pointer van een array op zijn laatste element
- extract --
Importeer variabelen naar de current symbol table vanuit een array
- in_array -- Return TRUE if a value exists in an array
- key -- Fetch a key from an associative array
- krsort -- Sort an array by key in reverse order
- ksort -- Sort an array by key
- list --
Assign variables as if they were an array
- natcasesort --
Sort an array using a case insensitive "natural order" algorithm
- natsort --
Sort an array using a "natural order" algorithm
- next --
Advance the internal array pointer of an array
- pos -- Get the current element from an array
- prev -- Rewind the internal array pointer
- range --
Create an array containing a range of elements
- reset --
Set the internal pointer of an array to its first element
- rsort -- Sort an array in reverse order
- shuffle -- Shuffle an array
- sizeof -- Alias of count()
- sort -- Sort an array
- uasort --
Sort an array with a user-defined comparison function and
maintain index association
- uksort --
Sort an array by keys using a user-defined comparison function
- usort --
Sort an array by values using a user-defined comparison function
User Contributed Notes Array Functies |
add a note |
david at preform dot dk
01-Feb-1999 01:30 |
|
use the max function to get the highest value of an array e.g:
$maxval = max($array);
|
|
spinn at spinnwebe dot com
04-Apr-2001 10: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.
|
|
jeroen at php dot net
29-Aug-2001 08: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.
|
|
mlong at mlong dot org
29-Jan-2002 10: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.
|
|
php dot net at chiefworks dot com
05-Feb-2002 06: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']}!";
?>
|
|
bfair at logix3N0SPAM dot com
14-Apr-2002 10:34 |
|
Looping through an array, and printing each item:
for ($i = 0; $i
< count($array_name); $i++) { echo("$i - $arrayname[$i]"); }
|
|
support at adventure-miami dot com
20-Apr-2002 01: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
|
|
josh at mirtec dot net
29-May-2002 03:17 |
|
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], [[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 06: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);
|
|
spam (at) speedcapture . com
15-Jun-2002 02: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.' </td>'; if
(is_array($elem1)) { extArray($elem1); } else { echo
'<td>'.$elem1.' </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.' </td>'; if (is_array($elem))
{ extArray($elem); } else { echo
'<td>'.htmlspecialchars($elem).' </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 06: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");
|
|
michael at ettl dot co dot at
29-Jul-2002 01: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; }
|
|
dan at kuykendall dot org
23-Aug-2002 10: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; }
|
|
J. Dyer (jkdyer_at_vlsmaps_dot_com)
10-Sep-2002 09:55 |
|
As it has been stated before, array_pop and the splice-derived functions
re-index any associatively defined elements..
// bad array
example $array[5] = "foo"; $array[6] =
"bar"; $var = array_pop($array); $key = key($array); //
$key would be 0, not 5 as would be expected for the value
"foo".
Instead, keep your keys/associations by using the
unset() function.
// better array example end($array); $key =
key($array); unset($array[$key]); // now the other keys/values
aren't touched.
... This will remove the last entry in your array,
but not re-index it. In this manner, you won't lose your associations.
It has been tested and seems to work fine.
|
|
ifrostNOSPAM at uos dot de
14-Sep-2002 05:59 |
|
A simple way to print the structure and the values of an array:
echo
'<pre>'; print_r($my_array); echo '</pre>';
|
|
adam dot swick at NOSPAM dot pantellos dot com
21-Sep-2002 08:03 |
|
Multidimensional lookup sample
db
table ================== name.....type -----....------- Judy.....Brunette Jackie...Blonde Jill.....Redhead
code ===================
$key = 0; while ($row=mssql_fetch_array($result)) {
$TPType["Name"][$key] = $row["name"];
$TPType["Type"][$key] = $row["type"];
$key++; }
$searchName = "Jill"; $key =
array_search ($searchName, $TPType["Name"]);
$searchName .= "
(".$TPType["Type"][$key].")";
results =============== Jill
(Redhead)
|
|
contact at chezjulien . com
26-Sep-2002 01:33 |
|
If you want to delete a value from an array, here's a function which will
suit your needs:
<pre> function array_delete_value($array,
$value) { for($i=0;$i<count($array);$i++) { if ($array[$i] ==
$value) unset($array[$i]); if(!isset($array[$i])) { $array[$i]
= $array[$i+1]; unset($array[$i+1]); } } return
$array; } </pre>
Hope this helps,
Julien, from
France
|
|
atnak at chejz dot com
26-Nov-2002 07:12 |
|
Here's a function that will set an arbitary array field to an arbitary
value:
function array_field_to_value(&$array, $field,
$value) { if ( is_array($field) ) { $head =
array_shift($field);
if ( count($field) == 0 )
{ $array[$head] = $value; } else
{ array_field_to_value($array[$head], $field,
$value); } } else {
$array[$field] = $value; } }
I find this useful for doing
things like this:
$post_arg =
"1,10,pizza,orange,cat"; $post_val =
"something";
$myarray =
array(); array_field_to_value($myarray, explode(',', $post_arg),
$post_val);
Which gets the same results as doing:
$myarray =
array(); $myarray['1']['10']['pizza']['orange']['cat'] =
"something";
|
|
mailman(AT)hit-squad.net
05-Dec-2002 01:30 |
|
I noticed a lack of a function to insert a value into a specified place in
an array. Here'a a function I came up with that will do
this:
function array_insert(&$array, $value, $pos) {
if (!is_array($array)) return FALSE;
$last =
array_splice($array, $pos);
array_push($array, $value);
$array = array_merge($array, $last); }
It can be used like
this:
$a = array("zero", "one",
"two", "three", "four", "five",
"six", "seven",
"eight"); array_insert($a, "POOP", 4);
The
array will now contain: ("zero", "one",
"two", "three", "POOP", "four",
"five", "six", "seven", "eight")
|
|
wheaty at planetquake dot com
17-Dec-2002 01:34 |
|
In keeping with OO principles in PHP4, if you want to pass a reference of
an array to an object (instead of using ugly global
variables):
================================== class A {
var $myarray;
// constructor function A (
&$array_param ) { $this->myarray =&
$array_param; }
function put_hi() {
$this->myarray[] = "Hi!"; } }
$greetings
= array("Hello.", "How are you doing?", "What's
up?");
$myobj =& new
A($greetings); $myobj->put_hi();
print_r($greetings); ==================================
Will
Output:
Array ([0] => Hello. [1] => How are you doing? [2]
=> What's up? [3] => Hi!)
|
|
mno11 at lycos dot NOSPAM
27-Dec-2002 10:41 |
|
For those that would like something similar to print_r, but instead returns
the values as a string, I've written the following simple function. It
doesn't work for 3D arrays, yet...
function arrayData($array)
{ $keys = array_keys($array); $values =
array_values($array); $data = ""; for
($i=0; $i<count($keys); $i++) { $data .=
$keys[$i]."=>'".$values[$i]."' , ";
} return $data; }
To email me, replace NOSPAM
with com
|
|
jon at pixelmajik dot com
30-Dec-2002 08:10 |
|
A little function which rotates a 2d array (or, basically, swaps the first
two keys of a multidimensional array). Oh, and it's hash-friendly (hence
my use of foreach instead of for).
Example
1: $a['alice']['gender'] = 'f'; $a['alice']['status'] =
'single'; $a['bob']['gender'] = 'm'; $a['bob']['status'] =
'married'; $a['charles']['gender'] =
'm'; $a['charles']['status']='divorced'; $b =
array_rotate_2d($a);
print_r($b) results in:
Array (
[gender] => Array ( [alice] => f
[bob] => m [charles] => m )
[status] => Array ( [alice] =>
single [bob] => married [charles] =>
divorced ) )
As you may see, it's useful for
displaying rows as columns (example 2, below) or reorganizing data
(example 1, above).
Example 2: $qid = mysql_query("SELECT
... FROM table"); while($row = mysql_fetch_array($qid,
MYSQL_ASSOC)) $table[] = $row; $rotated_table =
array_rotate_2d($table); foreach($table AS $row) { echo
join("\t", $row)."\n"; }
Code: function
array_rotate_2d($old) { // rotates a 2d array such that
$array[$i][$j] becomes $array[$j][$i]. (useful for displaying rows as
columns, for example)
foreach($old AS $k1=>$v1)
foreach($v1 AS $k2=>$v2) $new[$k2][$k1] = $v2;
return
$new; }
|
|
philNOSPAMippe at moNO-SPAMrange dot n-e-t
08-Jan-2003 03:35 |
|
Hi, I took the function from spam (at) speedcapture . com I
simplified it just a little, and here is the result. Thanks for sharing
this great tool with us. Simple, but sooooo usefull :)
function
view_array($arr, $td=0) { if ($td) { echo
'<td>'; } echo '<table>'; foreach ($arr
as $key => $elem) { echo '<tr>'; echo
'<td>'.$key.' </td>'; if (is_array($elem))
{ view_array($elem, 1); } else {
echo
'<td>'.htmlspecialchars($elem).' </td>';
} echo '</tr>'; } echo
'</table>'; if ($td) { echo '</td>';
} }
You call it as you used to: Let $myArray be an array of
any kind, simply do view_array($myArray);
|
|
brian at exclamationlabs dot com
10-Jan-2003 11:47 |
|
Frederic Maybaum in newsgroups gave me this solution. If you are coming
from perl and want to get the -1, -2, etc of an array, you don't have this
convention in PHP, there is no $array[-1].
So here are 2
solutions:
$stuff = array('lard','utensil','pig','roasting
spit');
to get 'roasting spit' you can do this: print
end($stuff) ."\n";
If your looking for something a little
more flexible: print $stuff[count($stuff) - 1] ."\n"; //
'roasting spit' print $stuff[count($stuff) - 2] ."\n"; //
'pig'
This is handy if you are looking for a quick method to grab a
filename from a fully qualified filename variable:
$filename =
"/usr/local/proggy/bin/goober"; print
end(preg_split("|\/|",$filename)) ."\n"; // <--
goober
Thanks Frederic!
|
|
telefoontoestel at officexpert dot digitaal dot biz
12-Feb-2003 06:13 |
|
I've created a small function for the optimization of an array. It removes
all empty elements and sets the next filled element to the place the empty
element was. It is a function wich argument is passed by reference, so it
will only return true, in case the value of the argument was correct or
false if the value was incorrect.
function arOpt(&$array){ //
pass by reference if(!is_array($array)){
return false; } $temp; // create a temporary
array; for($i = 0; $i < sizeof($array); $i++){
if(!empty($array[$i])){
$temp[sizeof($temp)] = $array[$i]; } }
$array = $temp; return true; }
|
|
programming at shrum dot net
14-Feb-2003 08:50 |
|
Using a foreach loop vs. a for loop
This may be a better way to
traverse an associative array:
foreach (array_keys($array_name)
as $key) { echo($array_name[$key] . " ");
}
In case anybody is wondering.
|
|
josh NO at SPAM mirtec dot net
17-Feb-2003 05:05 |
|
Instant JavaScript array from PHP array (any combination of associative /
numeric sub-arrays):
function arrayToJS ($theArray,
$jsArrayName) { $jsArrayString = $jsArrayName . " = new
Array ();\n"; foreach ($theArray as $key => $val)
{ if (is_numeric ($key)) { $jsElement
= $key; } else {
$jsElement = '\'' . $key . '\''; } if (is_array
($val)) { $jsArrayString .= arrayToJS ($val,
$jsArrayName . '[' . $jsElement . ']'); } else
{ if (is_numeric ($val)) {
$jsValue = $val; } else
{ $jsValue = '\'' . $val . '\''; }
$jsArrayString .= $jsArrayName . '[' . $jsElement
. '] = ' . $jsValue . ";\n"; } }
return
$jsArrayString; }
//----------------usage------------------//
echo
'<script language="JavaScript"
type="text/javascript">'; echo arrayToJS ($myArray,
'myJSArray'); echo '</script>';
// for some reason the PHP
site keeps scrambling my indentation .. :(
|
|
Frank
09-Mar-2003 11:34 |
|
After doing a lot of research i discovered that multidimensional arrays did
not work as some people explained.
Suppose the table
"Projecten"
contains: project_id,project_omschrijving 1,first 2,second
And
using the next code
$proj_result = pg_query("SELECT * FROM
\"Projecten\"") or die (pg_last_error());
if
($myrow = pg_fetch_array($proj_result)) { do
{ $proj[][0]=$myrow["project_id"]; $proj[][1]=$myrow["project_omschrijving"]; }
while ($myrow = pg_fetch_array($proj_result)); }
Would create an
array: $proj[0][0]=1 $proj[0][1]=first $proj[1][0]=2 $proj[1][1]=second
I
would then expect foreach( $proj as $s) to give me: $s as an array
containing(1,first) and the next foreach loop would give me an array
$s=(2,second). But this is not working here. It returns (first)
So
be carefull when using foreach and the other walkers of arrays when using
mutliple dimension arrays.
Be prepared to walk value by value and
act accordingly.
This took me sometime to figure out.
|
|
rudecoder at yahoo dot com
25-Mar-2003 04:52 |
|
Here's a tested function that will help you swap array elements with
minimal effort.
function
reposition($myarray,$oldpos,$newpos){
$temparray =
$myarray; for($i=0; $i < count($myarray);
$i++){ if($i == $oldpos){
$temparray[$newpos] = $myarray[$i]; }
if($i == $newpos){ $temparray[$oldpos] =
$myarray[$i]; } } return
$temparray; }
// Example of use...
$most_popular =
array("Seineld","Elaine","Kramer","George");
//
Now let's make Elaine more popular then Kramer $most_popular =
reposition($most_popular,3,1);
//Now we have an array with Elaine
and George in swapped positions: //$most_popular[0] =
"Seinfeld"; //$most_popular[1] =
"George"; //$most_popular[2] =
"Kramer"; //$most_popular[3] = "Elaine";
|
|
alban dot medici at fr dot netcentrex dot net
26-Mar-2003 04:18 |
|
If you want to simply remove a couple (key - value) from an indexes array ,
use the unset function as :
$yourArray = array("Key1"
=> toto, "key2" => titi,
"badKey" => value);
// you
make your treatment and whant to remove the badKey // cause not useful
anymore ...
unset($yourArray[badKey]);
//then your array
look like this : $yourArray[Key1] = toto $yourArray[key2] = titi
|
|
brian at stkinternational dot com
02-May-2003 03:10 |
|
I needed an easy way to move around the internal pointer of an array in
place. Here are a couple of functions that I put together out of
necessity.
/** * @return void * @param $array array *
@param offset int * @desc Set internal array pointer to absolute
offset */ function aseek(&$array, $offset) { if (
$offset >= 0 ) { reset($array); while (--$offset
> 0) { next($array); } } else
{ end($array); while (++$offset < 0) {
prev($array); } } }
/** * @return void *
@param $array array * @param offset int * @desc Set internal array
pointer to relative offset */ function rseek(&$array,
$offset) { if ($offset > 0) { while ($offset--
> 0) { next($array); } } else
{ while ($offset++ < 0) { prev($array);
} } }
|
|
dave at NOSPAM dot daveswave dot net
19-May-2003 02:01 |
|
To remove all elements in one array from another array:
function
array_delete_value($array, $value) { unset ($array[$value]);
return $array; } function array_minus_array ($array1, $array2) {
foreach ($array1 as $key => $val) { foreach ($array2 as
$item => $content) { if ($content==$val) {
$array1 = array_delete_value ($array1, $key); } }
} return ($array1); }
|
|
add a note |
| |