phpday 2027 - Call for Papers

Arrays

Introduzione

Queste funzioni permettono di interagire con gli array e di manipolarli in diversi modi. Gli array sono essenziali per memorizzare, gestire e operare su insiemi di variabili.

Sono supportati array semplici e multidimensionali, che possono essere creati dall'utente o da un'altra funzione. Ci sono specifiche funzioni per interagire con i database che popolano gli array con i risultati delle query, e diverse funzioni restituiscono array.

Si veda la sezione Array del manuale per una spiegazione dettagliata di come gli array sono implementati e usati in PHP. Si vedano anche gli operatori di Array per conoscere altri modi con cui manipolare gli array.

  • Costanti predefinite
  • Sorting Arrays
  • Array Funzioni
    • array — Crea un array
    • array_all — Verifica se tutti gli elementi di un array soddisfano una funzione callback
    • array_any — Verifica se almeno un elemento di un array soddisfa una funzione callback
    • array_change_key_case — Cambia case a tutte le chiavi dell'array
    • array_chunk — Divide un array in più subarray
    • array_column — Return the values from a single column in the input array
    • array_combine — Crea un array utilizzando un array per le chiavi e un altro per i suoi valori
    • array_count_values — Conta tutte le occorrenze di ogni singolo valore in un array
    • array_diff — Calcola la differenza tra array
    • array_diff_assoc — Calcola la differenza tra array con un ulteriore controllo sull'indice
    • array_diff_key — Computes the difference of arrays using keys for comparison
    • array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function
    • array_diff_ukey — Computes the difference of arrays using a callback function on the keys for comparison
    • array_fill — Riempie un array con dei valori
    • array_fill_keys — Fill an array with values, specifying keys
    • array_filter — Filtra gli elementi di un array usando una funzione callback
    • array_find — Restituisce il primo elemento che soddisfa una funzione callback
    • array_find_key — Restituisce la chiave del primo elemento che soddisfa una funzione callback
    • array_first — Restituisce il primo valore di un array
    • array_flip — Scambia tutte le chiavi di un array con i valori ad esse associati
    • array_intersect — Calcola l'intersezione tra array
    • array_intersect_assoc — Calcola l'intersezione tra array con un ulteriore controllo sull'indice
    • array_intersect_key — Computes the intersection of arrays using keys for comparison
    • array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function
    • array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison
    • array_is_list — Verifica se un array specificato è una lista
    • array_key_exists — Controlla se la chiave o l'indice specificato esiste nell'array
    • array_key_first — Restituisce la prima chiave di un array
    • array_key_last — Restituisce l'ultima chiave di un array
    • array_keys — Restituisce tutte le chiavi, o un sottoinsieme delle chiavi, di un array
    • array_last — Restituisce l'ultimo valore di un array
    • array_map — Applica la callback agli elementi degli array forniti
    • array_merge — Fonde uno o più array
    • array_merge_recursive — Fonde uno o più array ricorsivamente
    • array_multisort — Ordina array multipli o multidimensionali
    • array_pad — Riempie un array fino alla lunghezza specificata con un valore
    • array_pop — Estrae l'elemento alla fine dell'array
    • array_product — Calculate the product of values in an array
    • array_push — Inserisce uno o più elementi alla fine dell'array
    • array_rand — Sceglie una o più chiavi casuali da un array
    • array_reduce — Riduce iterativamente l'array a un singolo valore usando una funzione callback
    • array_replace — Replaces elements from passed arrays into the first array
    • array_replace_recursive — Sostituisce ricorsivamente nel primo array gli elementi provenienti dagli array passati
    • array_reverse — Restituisce un array con gli elementi in ordine inverso
    • array_search — Cerca un valore in un array e, se lo trova, restituisce la prima chiave corrispondente
    • array_shift — Estrae un elemento dall'inizio dell'array
    • array_slice — Estrae una porzione dell'array
    • array_splice — Rimuove una porzione dell'array e la sostituisce con altro
    • array_sum — Calcola la somma dei valori di un array
    • array_udiff — Computes the difference of arrays by using a callback function for data comparison
    • array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function
    • array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by a callback function
    • array_uintersect — Computes the intersection of arrays, compares data by a callback function
    • array_uintersect_assoc — Computes the intersection of arrays with additional index check, compares data by a callback function
    • array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions
    • array_unique — Rimuove i valori duplicati da un array
    • array_unshift — Aggiunge uno o più elementi all'inizio di un array
    • array_values — Restituisce tutti i valori di un array
    • array_walk — Applica una funzione definita dall'utente a ogni elemento di un array
    • array_walk_recursive — Apply a user function recursively to every member of an array
    • arsort — Ordina un array in ordine decrescente mantenendo l'associazione degli indici
    • asort — Ordina un array in ordine crescente mantenendo l'associazione degli indici
    • compact — Crea un array contenente variabili e i loro valori
    • count — Conta tutti gli elementi di un array o di un oggetto Countable
    • current — Restituisce l'elemento corrente di un array
    • each — Restituisce la coppia chiave/valore corrente di un array e fa avanzare il cursore dell'array
    • end — Imposta il puntatore interno di un array al suo ultimo elemento
    • extract — Importa le variabili nella symbol table corrente a partire da un array
    • in_array — Controlla se un valore esiste in un array
    • key — Estrae una chiave da un array
    • key_exists — Alias di array_key_exists
    • krsort — Ordina un array per chiave in ordine decrescente
    • ksort — Ordina un array per chiave in ordine crescente
    • list — Assegna valori a variabili come se fossero un array
    • natcasesort — Ordina un array usando un algoritmo di "ordinamento naturale" senza distinguere tra maiuscole e minuscole
    • natsort — Ordina un array usando un algoritmo di "ordinamento naturale"
    • next — Fa avanzare il puntatore interno di un array
    • pos — Alias di current
    • prev — Riporta indietro il puntatore interno dell'array
    • range — Crea un array contenente un intervallo di elementi
    • reset — Imposta il puntatore interno di un array al suo primo elemento
    • rsort — Ordina un array in ordine decrescente
    • shuffle — Mescola un array
    • sizeof — Alias di count
    • sort — Ordina un array in ordine crescente
    • uasort — Ordina un array con una funzione di confronto definita dall'utente mantenendo l'associazione degli indici
    • uksort — Ordina un array per chiave usando una funzione di confronto definita dall'utente
    • usort — Ordina un array per valore usando una funzione di confronto definita dall'utente

User Contributed Notes 8 notes

up
106
applegrew at rediffmail dot com
18 years ago
For newbies like me.

Creating new arrays:-
//Creates a blank array.
$theVariable = array();

//Creates an array with elements.
$theVariable = array("A", "B", "C");

//Creating Associaive array.
$theVariable = array(1 => "http//google.com", 2=> "http://yahoo.com");

//Creating Associaive array with named keys
$theVariable = array("google" => "http//google.com", "yahoo"=> "http://yahoo.com");

Note:
New value can be added to the array as shown below.
$theVariable[] = "D";
$theVariable[] = "E";
up
24
Tyler Bannister
17 years ago
To delete an individual array element use the unset function

For example:

<?PHP
    $arr = array( "A", "B", "C" );
    unset( $arr[1] );
    // now $arr = array( "A", "C" );
?>

Unlink is for deleting files.
up
7
macnimble at gmail dot com
17 years ago
Converting a linear array (like a mysql record set) into a tree, or multi-dimensional array can be a real bugbear. Capitalizing on references in PHP, we can 'stack' an array in one pass, using one loop, like this:

<?php
# array_stack()
# Original idea from:
# http://www.ideashower.com/our_solutions/
#   create-a-parent-child-array-structure-in-one-pass/
function array_stack (&$a, $p = '@parent', $c = '@children')
{
  $l = $t = array();
  foreach ($a AS $key => $val):
    if (!$val[$p]) $t[$key] =& $l[$key];
    else $l[$val[$p]][$c][$key] =& $l[$key];
    $l[$key] = (array)$l[$key] + $val;
  endforeach;
  return $a = array('tree' => $t, 'leaf' => $l);
}

# Example:
$node = array();
$node[1] = array('@parent' => 0, 'title' => 'I am node 1.');
#     ^-----------------------v Link @parent value to key.
$node[2] = array('@parent' => 1, 'title' => 'I am node 2.');
$node[3] = array('@parent' => 2, 'title' => 'I am node 3.');
$node[4] = array('@parent' => 1, 'title' => 'I am node 4.');
$node[5] = array('@parent' => 4, 'title' => 'I am node 5.');

array_stack($node);

$node['leaf'][1]['title'] = 'I am node one.';
$node['leaf'][2]['title'] = 'I am node two.';
$node['leaf'][3]['title'] = 'I am node three.';
$node['leaf'][4]['title'] = 'I am node four.';
$node['leaf'][5]['title'] = 'I am node five.';

echo '<pre>',print_r($node['tree'],TRUE),'</pre>';
?>

Note that there's no parameter checking on the array value, but this is only to keep the function size small. One could easily a quick check in there to make sure the $a parameter was in fact an array.

Hope you find it useful. Huge thanks to Nate Weiner of IdeaShower.com for providing the original function I built on.
up
2
dragos dot rusu at NOSPAM dot bytex dot ro
16 years ago
If an array item is declared with key as NULL, array key will automatically be converted to empty string '', as follows:

<?php
$a = array(
    NULL => 'zero',
    1    => 'one',
    2    => 'two');

// This will show empty string for key associated with "zero" value
var_dump(array_keys($a));

// Array elements are shown
reset($a);
while( key($a) !== NULL )
{
  echo key($a) . ": ".current($a) . "<br>";// PHP_EOL
  next($a);
}

// Array elements are not shown
reset($a);
while( key($a) != NULL ) // '' == null   => no iteration will be executed
{
  echo key($a) . ": ".current($a) . "<br>";// PHP_EOL
  next($a);
}
up
2
webmaster at infoproducts dot x10hosting dot com
18 years ago
New value can also be added to the array as shown below.
$theVariable["google"] = "http//google.com";
or
$theVariable["1"] = "http//google.com";
up
0
sunear at gmail dot com
17 years ago
Made this function to delete elements in an array;

<?php

function array_del_elm($input_array, $del_indexes) {
    if (is_array($del_indexes)) {
        $indexes = $del_indexes;
    } elseif(is_string($del_indexes)) {
        $indexes = explode($del_indexes, " ");
    } elseif(is_numeric($del_indexes)) {
        $indexes[0] = (integer)$del_indexes;
    } else return;
    $del_indexes = null;
    
    $cur_index = 0;
    if (sort($indexes)) for($i=0; $i<count($input_array); $i++) {
        if ($i == $indexes[$cur_index]) {
            $cur_index++;
            if ($cur_index == count($indexes)) return $output_array;
            continue;
        }
        $output_array[] = $input_array[$i];
    }
    return $output_array;
}

?>

but then i saw the methods of doing the same by Tyler Bannister & Paul, could see that theirs were faster, but had floors regarding deleting multiple elements thus support of several ways of giving parameters. I combined the two methods to this to this:

<?php

function array_del_elm($target_array, $del_indexes) {
    if (is_array($del_indexes)) {
        $indexes = $del_indexes;
    } elseif(is_string($del_indexes)) {
        $indexes = explode($del_indexes, " ");
    } elseif(is_numeric($del_indexes)) {
        $indexes[0] = (integer)$del_indexes;
    } else return;
    unset($del_indexes);
    
    for($i=0; $i<count($indexes); $i++) {
        unset($target_array[$indexes[$i]]);
    }
    return $target_array;
}

?>

Fast, compliant and functional ;)
up
-4
info at curtinsNOSPAMcreations dot com
16 years ago
Another way to create a multidimensional array that looks a lot cleaner is to use json_decode.  (Note that this probably adds a touch of overhead, but it sure does look nicer.)  You can of course add as many levels and as much formatting as you'd like to the string you then decode.  Don't forget that json requires " around values, not '!!  (So, you can't enclose the json string with " and use ' inside the string.)

As an example:

<?php
    $myarray['blah'] = json_decode('[
        {"label":"foo","name":"baz"},
        {"label":"boop","name":"beep"}
    ]',true);

print_r($myarray)
?>
returns:

Array
(
    [blah] => Array
        (
            [0] => Array
                (
                    [label] => foo
                    [name] => baz
                )
 
            [1] => Array
                (
                    [label] => boop
                    [name] => beep
                )
        )
)
up
-2
andyd273 at gmail dot com
17 years ago
A small correction to Endel Dreyer's PHP array to javascript array function. I just changed it to show keys correctly:

            function array2js($array,$show_keys)
            {
                $dimensoes = array();
                $valores = array();
               
                $total = count ($array)-1;
                $i=0;
                foreach($array as $key=>$value){
                    if (is_array($value)) {
                        $dimensoes[$i] = array2js($value,$show_keys);
                        if ($show_keys) $dimensoes[$i] = '"'.$key.'":'.$dimensoes[$i];
                    } else {
                        $dimensoes[$i] = '"'.addslashes($value).'"';
                        if ($show_keys) $dimensoes[$i] = '"'.$key.'":'.$dimensoes[$i];
                    }
                    if ($i==0) $dimensoes[$i] = '{'.$dimensoes[$i];
                    if ($i==$total) $dimensoes[$i].= '}';
                    $i++;
                }
                return implode(',',$dimensoes);
            }
Adding new notes is disabled. Please see the links in the Found A Problem? section.
To Top