PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Objetos> <Strings
Last updated: Fri, 22 Aug 2008

view this page in

Arrays

Um array no PHP é atualmente um mapa ordenado. Um mapa é um tipo que relaciona valores para chaves. Este tipo é otimizado de várias maneiras, então você pode usá-lo como um array real, ou uma lista (vetor), hashtable (que é uma implementação de mapa), dicionário, coleção, pilha, fila e provavelmente mais. Como você pode ter outro array PHP como um valor, você pode facilmente simular árvores.

A explicação dessas estruturas estão além do escopo desse manual, mas você pode encontrar exemplos para cada uma dessas estruturas a seguir. Para mais informações sobre estruturas, refira-se a literatura externa sobre esses tópicos.

Sintaxe

Especificando com array()

Um array pode ser criado com o construtor de linguagem array(). Ele pega um certo número de pares separados por vírgula chave => valor .

array(  chave =>  valor
     , ...
     )
// chave pode ser tanto string ou um integer
// valor pode ser qualquer coisa
    

<?php
$arr 
= array("foo" => "bar"12 => true);

echo 
$arr["foo"]; // bar
echo $arr[12];    // 1
?>

A chave pode ser tanto um integer ou uma string. Se a chave é uma representação padrão de um integer, ele será interpretado assim (por exemplo, "8" será interpretado como 8, enquanto "08" será interpretado como "08"). Flotas em key são truncados para integer. Não há diferença entre arrais indexados e associativos em PHP, apenas um tipo de array, que pode ter índices inteiros ou string.

O valor pode ser qualquer tipo PHP:

<?php
$arr 
= array("somearray" => array(=> 513 => 9"a" => 42));

echo 
$arr["somearray"][6];    // 5
echo $arr["somearray"][13];   // 9
echo $arr["somearray"]["a"];  // 42
?>

Se omitir a chave quando fornece um novo item, o maior índice inteiro é obtido, e a nova chave será esse máximo + 1. Se você especificar uma chave que já possui um valor assimilada a ela, então o valor é sobrescrito.

<?php
// Esse array é como ...
array(=> 433256"b" => 12);

// ... este array
array(=> 43=> 32=> 56"b" => 12);
?>

Aviso

A partir do PHP 4.3.0, o comportamento da geração de índice descrito acima foi modificado. Agora, se você aumentar um array em que o maior índice atual for negativo, então a próxima chave criada será zero (0). Antes, o novo índice seria o maior índice existente mais 1, do mesmo jeito que os índices positivos.

Utilizar TRUE como chave será interpretado como o integer 1 na chave. Utilizando FALSE como chave será avaliado como o integer 0. Usar NULL como chave é interpretado como uma string vazia. Usar uma string vazia como chave irá criar (ou sobrescerver) uma chave com uma string vazia e seu valor, e isto não é o mesmo que usar colchetes vazios.

Você não pode usar arrays ou objetos como chaves. Fazendo isso resultará em um alerta: Illegal offset type.

Criando/modificando com a sintaxe de colchetes

Você pode também modificar um array existente explicitamente assimilando valores nele.

Isto é feito apenas assimilando valores para o array enquanto especificando a chave em colchetes. Você pode omitir a chave, colocando um par vazio de colchetes ("[]").

$arr[chave] = valor;
$arr[] = valor;
// chave tanto um integer ou string
// valor pode ser qualquer coisa
    
Se $arr não existir ainda, ele será criado. Então isto é um meio alternativo para especificar um array. Para mudar um certo valor, apenas assimile um novo valor para um elemento especificado por sua chave. Se você quiser remover um par chave/valor, você precisa aplicar unset() nele.
<?php
$arr 
= array(=> 112 => 2);

$arr[] = 56;    // Isto é o mesmo que $arr[13] = 56;
                // nesse ponto do script

$arr["x"] = 42// Isto acrescenta um novo elemento
                // para o array com a chave "x"

unset($arr[5]); // Isto remove um elemento do array

unset($arr);    // E isto apaga todo o array
?>

Nota: Como mencionado acima, não informar a chave dentro dos colchetes, então o maior índice inteiro é obtido, e a nova chave será esse máximo + 1. Se nenhum índice inteiro existir ainda, a chave será 0 (zero). Se você especificar uma chave que já possui um valor assimilada a ela, então o valor é sobrescrito.

Aviso

A partir do PHP 4.3.0, o comportamento da geração de índice descrito acima foi modificado. Agora, se você aumentar um array em que o maior índice atual for negativo, então a próxima chave criada será zero (0). Antes, o novo índice seria o maior índice existente mais 1, do mesmo jeito que os índices positivos.


Note que a chave inteira maior utilizada para isso não precisa necessariamente existir no array. Ele pode ter existido no array desde a última vez que o array foi indexado. Veja o seguinte exemplo:
<?php
// Criando um array normal
$array = array(12345);
print_r($array);

// Agora apagando todos os itens, mas deixando o array intacto:
foreach ($array as $i => $value) {
    unset(
$array[$i]);
}
print_r($array);

// Acrescentando um item (note que a chabe é 5, em vez de zero
// como voce pode ter esperado).
$array[] = 6;
print_r($array);

// Reindexando:
$array array_values($array);
$array[] = 7;
print_r($array);
?>

O exemplo acima irá imprimir:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
)
Array
(
    [5] => 6
)
Array
(
    [0] => 6
    [1] => 7
)

Funções úteis

Há uma série de funções muito úteis para trabalhar com arrays. Veja a seção sobre arrays.

Nota: A função unset() permite apagar chaves de um array. Esteja avisado que o array NÃO vai ser reindexado. Se você somente usa "índices inteiros comuns" (começando do zero, aumentando um a um), você pode conseguir reindexar o aaray utilizando array_values().

<?php
$a 
= array( => 'um'=> 'dois'=> 'três' );
unset( 
$a[2] );
/* irá produzir um array que pode ser definido como
   $a = array( 1=>'um', 3=>'três');
   e NÃO
   $a = array( 1 => 'um', 2 => 'três');
*/

$b array_values($a);
// Agora $b é o  array(1 => 'um', 2 =>'três')
?>

foreach existe especificamente para lidar com arrays. Ele provém uma maneira fácil de percorrer qualquer array.

Array: faça e não faça

Porque $foo[bar] está errado?

Você sempre deve usar delimitadores em volta um índice de um array associativo. Por exemplo, utilizar $foo['bar'] e não $foo[bar]. Mas porque $foo[bar] está errado? Afinal de contas, você vê essa sintaxe nos scripts antigos:

<?php
$foo
[bar] = 'inimigo';
echo 
$foo[bar];
// etc
?>
Isto está errado, mas funciona. Então, porque está errado? A razão está neste código, que tem uma constante indefinida (bar) em vez de uma string ('bar' - repare nos delimitadores), e o PHP pode no futuro definir constantes que, infelizmente em seu código, podem ter o mesmo nome. Isto funciona, porque o PHP automaricamente converte uma string base (uma string não delimitada que não corresponde a nenhum símbolo conhecido) em uma string que contém a string base. Por exemplo, se não existir uma constante definida com o nome bar, então o PHP irá substituí-la pela string 'bar' e usá-la.

Nota: Isto não significa que você sempre deve delimitar as chaves nos arrays. Você não deve delimitar chaves que sejam constantes ou variáveis, porque isso vai impedir o PHP de interpretá-las.

<?php
error_reporting
(E_ALL);
ini_set('display_errors'true);
ini_set('html_errors'false);
// Arrays simples:
$array = array(12);
$count count($array);
for (
$i 0$i $count$i++) {
    echo 
"\nVerificando $i: \n";
    echo 
"Ruim: " $array['$i'] . "\n";
    echo 
"Bom: " $array[$i] . "\n";
    echo 
"Ruim: {$array['$i']}\n";
    echo 
"Bom: {$array[$i]}\n";
}
?>
O exemplo acima irá imprimir:
Verificando 0:
Notice: Undefined index:  $i in /path/to/script.html on line 9
Ruim:
Bom: 1
Notice: Undefined index:  $i in /path/to/script.html on line 11
Ruim:
Bom: 1

Verificando 1:
Notice: Undefined index:  $i in /path/to/script.html on line 9
Ruim:
Bom: 2
Notice: Undefined index:  $i in /path/to/script.html on line 11
Ruim:
Bom: 2

Mais exemplos para demonstrar esse fato:

<?php
// Vamos ver todos os erros
error_reporting(E_ALL);

$arr = array('fruta' => 'maçã''legume' => 'cenoura');

// Correto
print $arr['fruta'];  // maçã
print $arr['legume']; // cenoura

// Errado. Isto funciona mas lança um erro PHP do
// nível E_NOTICE porque é utilizada uma constante indefinida (fruta)
// 
// Repare: Quando utiliza-se a constrante indefinida fruta, o PHP assume 'fruta'
print $arr[fruta];    // maçã

// Agora vamos definir uma constante para demonstrar o que pode acontecer. Nós
// vamos assimilar o valor 'legume' para a constante de nome fruta
define('fruta''legume');

// Observe a diferenca agora
print $arr['fruit'];  // maçã
print $arr[fruit];    // cenoura

// O exemplo seguinte é normal dentro de uma string. Constantes não são
// observadas dentro de strings e por isso nenhum E-NOTICE não é lançado aqui
print "Olá $arr[fruta]";      // Olá maçã

// Com uma exceção: chaves envolvendo arrays dentro de strings
// ativam a checagem de constantes, como em
print "Olá {$arr[fruta]}";    // Hello cenoura
print "Olá {$arr['fruta']}";  // Hello maçã

// E isso não funciona, resultando em um erro de interpretação do tipo:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// Isso se aplica ao uso de superglobais em strings
print "Olá $arr['fruta']";
print 
"Olá $_GET['foo']";

// Nesse caso, use concatenacao
print "Olá " $arr['fruta']; // Olá maçã
?>

Quando você ativa error_reporting() para mostrar erros de nível E_NOTICE (como configurando-a para E_ALL) você vê esses erros. Por padrão, error_reporting esté configurada para não mostrar esse nível de erro.

Como explicado na seção sintaxe, a chave precisa estar entre colchetes ('[' e ']'). Isto significa que você pode escrever coisas como isso:

<?php
echo $arr[algumafuncao($bar)];
?>
Isto é um exemplo de utilização de um valor de retorno de função como um índice de array. O PHP conhece constantes, como você deve ter visto algumas E_* antes.
<?php
$error_descriptions
[E_ERROR] = "Um erro fatal ocorreu";
$error_descriptions[E_WARNING] = "O PHP emitiu um alarme";
$error_descriptions[E_NOTICE] = "Apenas um aviso informal";
?>
Note que E_ERROR é um identificador válido, assim como bar no primeiro exemplo. Mas no último exemplo seria a mesma coisa que escrevendo:
<?php
$error_descriptions
[1] = "Um erro fatal ocorreu";
$error_descriptions[2] = "O PHP emitiu um alarme";
$error_descriptions[8] = "Apenas um aviso informal";
?>
porque E_ERROR é igual a 1, e assim por diante.

Como nós mostramos nos exemplos anteriores, $foo[bar] funciona mas está errado. Funciona porque bar, na sintaxe onde é utilizada é esperada como uma expressão constante. Entretanto, nesse caso não existe constante com o nome bar. O PHP, hoje, assume que você quer bar literalmente, como a string "bar", mas que você esqueceu de escrever os delimitadores.

Então, porque isso é tão mal?

Se em algum ponto do futuro, o time do PHP quiser acrescentar outra constante ou palavra chave, ou você mesmo introduzir outra constante na sua aplicação, você terá problemas. Por exemplo, se você já não pode utilizar as palavras empty e default dessa maneira, desde que elas são palavras reservadas especiais.

Nota: Só para fixar, dentro de uma string delimitada por aspas, é válido não englobar índices de arrays com apóstrofos, de forma que "$foo[bar]" é válido. Veja os exemplos anteriores para detalhes bem como na seção sobre interpretação de variáveis em strings.

Convertendo para array

Para qualquer dos tipos: integer, float, string, boolean e resource, se você converte um valor para um array, você obtêm um array com um elemento (de índice 0) contendo o valor escalar informado.

Se você converte um tipo object para um array, você obtêm as propriedades (variáveis membro) do objeto com elementos do array. As chaves serão o nome das variáveis membro com pequenas notáveis exceções: variáveis privada tem o nome da classe prefixado no nome da variável; variáveis protegidas tem um '*' prefixando o nome da variável. Estes prefixos tem null bytes em ambos os lados. Isto pode resultado em algum comportamente inesperado.

<?php

class {
    private 
$A// This will become '\0A\0A'
}

class 
extends {
    private 
$A// This will become '\0B\0A'
    
public $AA// This will become 'AA'
}

var_dump((array) new B());
?>
Acima aparece duas chaves chamadas 'AA', embora uma delas é atualmente chamada '\0A\0A'.

Se você converter um valor NULL para um array, você terá um array vazio.

Comparando

É possível comparar arrays através de array_diff() e operadorores de array.

Exemplos

O tipo array do PHP é muito versátil, por isso temos aqui alguns exemplos para mostrar todo o poder dos arrays.

<?php
// isto
$a = array( 'cor'   => 'vermelha',
            
'sabor' => 'doce',
            
'forma' => 'redonda',
            
'nome'  => 'maçã',
                       
4        // a chave será 0
          
);

// isto é equivalente a acima
$a['cor']   = 'vermelha';
$a['sabor'] = 'doce';
$a['forma'] = 'redonda';
$a['nome']  = 'maçã';
$a[]        = 4;        // a chave será 0

$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// o mesmo de array( 0 => 'a' , 1 => 'b' , 2 => 'c' ),
// ou simplesmente array('a', 'b', 'c')
?>

Exemplo #1 Utilizando array()

<?php
// Array como (propriedade-)mapa
$map = array( 'versao'     => 4,
              
'OS'         => 'Linux',
              
'lang'       => 'inglês',
              
'short_tags' => true
            
);

// apenas chaves numéricas
$array = array( 7,
                
8,
                
0,
                
156,
                -
10
              
);
// que é o mesmo que array( 0 => 7, 1 => 8, ...)

$switching = array(         10// chave = 0
                    
5    =>  6,
                    
3    =>  7,
                    
'a'  =>  4,
                            
11// chave = 6 (o índice máximo era 5)
                    
'8'  =>  2// chave = 8 (inteiro!)
                    
'02' => 77// chave = '02'
                    
0    => 12  // o valor 10 será sobrescrito por 12
                  
);

// array vazio
$empty = array();
?>

Exemplo #2 Coleção

<?php
$cores 
= array('vermelho''azul''verde''amarelo');

foreach (
$cores as $cor) {
    echo 
"Você gosta de $cor?\n";
}

?>

O exemplo acima irá imprimir:

Você gosta de vermelho?
Você gosta de azul?
Você gosta de verde?
Você gosta de amarelo?

Mudando diretamente valores de array é possível desde o PHP 5, passando-os como referência. Em versões anteriores precisava de um workaround:

Exemplo #3 Coleção

<?php
// PHP 5
foreach ($colors as &$color) {
    
$color strtoupper($color);
}
unset(
$color); /* ensure that following writes to
$color will not modify the last array element */

// Workaround for older versions
foreach ($colors as $key => $color) {
    
$colors[$key] = strtoupper($color);
}

print_r($colors);
?>

O exemplo acima irá imprimir:

Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)

Este exemplo cria um array na base 1.

Exemplo #4 Array baseado em 1

<?php
$primeiroquarto  
= array(=> 'Janeiro''Fevereiro''Março');
print_r($primeiroquarto);

?>

O exemplo acima irá imprimir:

Array
(
    [1] => 'Janeiro'
    [2] => 'Fevereiro'
    [3] => 'Março'
)

Exemplo #5 Preenchendo um array real

<?php
// preenchendo um array com todos os itens de um diretório
$handle opendir('.');
while (
false !== ($file readdir($handle))) {
    
$files[] = $file;
}
closedir($handle); 
?>

Arrays são ordenados. Você pode mudar sua ordem utilizando vários funções de ordenação. Veja as funções de arrays para mais informações. Você pode contar o número de itens de um array com a função count().

Exemplo #6 Ordenando arrays

<?php
sort
($files);
print_r($files);
?>

Porque o valor de um array pode ser qualquer coisa, isto pode ser outro array. Isto pode criar arrays recursivos e multidimensionais.

Exemplo #7 Arrays recursivos e multidimensionais

<?php
$fruits 
= array ( "frutas"  => array ( "a" => "laranja",
                                       
"b" => "banana",
                                       
"c" => "maçã",
                                     ),
                  
"numeros" => array ( 1,
                                       
2,
                                       
3,
                                       
4,
                                       
5,
                                       
6
                                     
),
                  
"buracos" => array (      "primeiro",
                                       
=> "segundo",
                                            
"terceiro",
                                     ),
                );

// Alguns exemplo de enderecos dos valores do array acima
echo $fruits["buracos"][5];   // prints "segundo"
echo $fruits["frutas"]["a"];  // prints "laranja"
unset($fruits["buracos"][0]); // remove "primeiro"

// Criando um novo array multidimensional
$sucos["maca"]["verde"] = "bom";
?>

Você precisa estar ciente que a atribuição sempre envolve cópia de valor. Também significa que o ponteiro interno do array usado por current() e funções similares são resetados. Você precisa utilizar o operador de referência para copiar um array por referência.

<?php
$arr1 
= array(23);
$arr2 $arr1;
$arr2[] = 4// $arr2 é modificado,
             // $arr1 continua sendo apenas array(2, 3)

$arr3 = &$arr1;
$arr3[] = 4// agora $arr1 e $arr3 sao os mesmos
?>



Objetos> <Strings
Last updated: Fri, 22 Aug 2008
 
add a note add a note User Contributed Notes
Arrays
pinkgothic at gmail dot com
13-Sep-2008 09:49
Re: fmouse,

the phenomenom you're describing pertains to superglobals, not arrays, and it only applies in a very specific scope. Check out http://de.php.net/manual/en/language.variables.variable.php :

"Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically."
frywater
04-Jun-2008 05:43
>fmouse

Variable variables can be used with arrays as discussed in the variable variable section.
Also, from your code, $somevar can be an array and still work fine.

$fum = "somevar";
$$fum = array(); // $somevar is now an array
$foo = $$fum;
print_r( $foo); // we get an empty array printed

print_r() doesn't just print arrays, it prints any variable type.
If you pass it a variable, that hasn't been defined yet, it won't know how to print it.

You would get this same results by passing any undefined variable such as:
print_r( $bar );  // PHP Notice: undefined variable ...$bar
fmouse at fmp dot com
29-Apr-2008 02:14
Using variables as array names no longer works in PHP5.

$fum = "somevar";
$foo = $$fum;

# Still works if $somevar isn't an array.  $foo contains the value of $somevar

but ....

$fum = "_POST";
print_r($$fum);
print_r(${$fum});

Neither form of indirection works in this context.  $$fum comes back empty.

If you have PHP4 code that used this kind of indirection you can work around the change in PHP5 using an eval().

$fum = "_POST";
$foo = eval("return $$fum;");
print_r($foo);

This works!
rama dot devi at gmail dot com
18-Mar-2008 03:52
Sorting double dimensional arrays by a specified key bothe for Strings and for integers:
Ex:
 
 $personDetails =  array( array("firstName" => "Nancy", "lastName" => "Grace", "age" => 22), array("firstName" => "Andy",  "lastName" => "Peter", "age" => 28),                           array("firstName" => "Jim",   "lastName" => "Gary",  "age" => 25), array("firstName" => "Lary",  "lastName" => "James", "age" => 28),  array("firstName" => "Peter", "lastName" => "David", "age" => 17), array("firstName" => "Raj",   "lastName" => "King",  "age" => 9),                           array("firstName" => "John",  "lastName" => "Baxter","age" => 35) );
//To sort the array by firstName:-
     function sortFirstName($p1, $p2) {
          return strnatcmp($p1['firstName'], $p2['firstName']);
      }
      usort($personDetails, 'sortFirstName');

//To sort by an integer Field

   function sortByInteger(&$personDetails, $field) {
      $sort = "return strnatcmp(\$p1['$field'], \$p2['$field']);";
       usort($personDetails, create_function('$p1,$p2', $sort));
        return $personDetails;
    }

    $personDetails = sortByInteger($personDetails, 'age');
//To sort the array in Descending order by a key, It can be done by adding "-" sign before strnatcmp() function.

I hope this helps
ken underscore yap atsign email dot com
09-Jan-2008 09:00
"If you convert a NULL value to an array, you get an empty array."

This turns out to be a useful property. Say you have a search function that returns an array of values on success or NULL if nothing found.

$values = search(...);

Now you want to merge the array with another array. What do we do if $values is NULL? No problem:

$combined = array_merge((array)$values, $other);

Voila.
pepesantillan at gmail dot com
18-Dec-2007 05:25
z on 22-Apr-2005 12:10 wrote:
-----------------------------------------------
Here's a simple function to insert a value into some position in an array

<?php
function array_insert($array,$pos,$val)
{
   
$array2 = array_splice($array,$pos);
   
$array[] = $val;
   
$array = array_merge($array,$array2);
  
    return
$array;
}
?>

and now for example...
<?php
$a
= array("John","Paul","Peter");
$a = array_insert($a,1,"Mike");
?>

Now $a will be "John","Mike","Paul","Peter"
-----------------------------------------------

Im learning to use PHP and reading about array_splice found that

<?php
function array_insert($array,$pos,$val)
{
   
$array2 = array_splice($array,$pos);
   
$array[] = $val;
   
$array = array_merge($array,$array2);

    return
$array;
}

$a = array("John","Paul","Peter");
$a = array_insert($a,1,"Mike");
print_r($a);
?>

would output the same as

<?php
$b
= array("John","Paul","Peter");
array_splice($b,1,0,array("Mike"));
print_r($b);
?>
SID TRIVEDI
10-Oct-2007 03:14
<?php

//Simple Login Script using associative array.

//You may modify the codes and use $_POST['FORM_FIELD_DATA'] for your web-page.
//You may spice-up the codes with more form field validation & security features.

//$user_name=$_POST['user_name'];
//$password=$_POST['password'];

$test_user_name = 'michelle_smith'; //for testing purpose only
$test_password = 'msmith321';        //for testing purpose only
$user_name = $test_user_name;
$password = $test_password;

// here user_name is key and password is the value of an array..
// website owner has to add new user/site member manually in $login_array

$login_array = array(
               
'user_name' => 'password',
               
'alex_duff' => 'alx321',
                   
'xena78' => 'xena321',
               
'dela_pena' => 'delp321',
               
'shawn_1981' => 'shw81',
               
'michelle_smith' => 'msmith321');

ksort ($login_array);
reset($login_array);
if (isset(
$login_array[$user_name]))
{
$pass_check = $login_array[$user_name];
if (
$password === $pass_check)
{
echo 
"Welcome, $user_name!\n<br>"; //may redirect to specific webpage.
}
else
{
echo
"Please try again!"; //may redirect to Error page.
}
}
else
{
    echo
"Please register with us. Thanks!"; //may redirect to registration page.
   
exit();
   
}
echo(
"\n<br>");
echo
'Thanks to Thies C. Arntzen, Stig Bakken, Shane Caraveo, Andi Gutmans, Rasmus Lerdorf, Sam Ruby, Sascha Schumann, Zeev Suraski, Jim Winstead, Andrei Zmievski for wonderful PHP!';

?>
carl at linkleaf dot com
06-Sep-2007 12:36
Its worth noting that there does not appear to be any functional limitations on the length or content of string indexes. The string indexes for your arrays can contain any characters, including new line characters, and can be of any length:

<?php

$key
= "XXXXX";
$test = array($key => "test5");

for (
$x = 0; $x < 500; $x++) {
 
$key .= "X";
 
$value = "test" . strlen($key);
 
$test[$key] = $value;
}

echo
"<pre>";
print_r($test);
echo
"</pre>";

?>

Keep in mind that using extremely long array indexes is not a good practice and could cost you lots of extra CPU time. However, if you have to use a long string as an array index you won't have to worry about the length or content.
Gautam
30-Aug-2007 02:56
<?php
//EXAMPLE  of Multi-Dimentional Array where as an array's keys are an array itself.
//It's so easy to create one like this.

$movie_to_watch = array ('Action'=>
          array(
'Kanu Reeves' => 'Matrix Reloaded',
                     
'Pearce Brosnan' => 'Die Another Day',
                     
'Tom Cruz' => 'Mission Impossible',
                     
'Jason Statham' => 'Crank',
                     
'Danzel Washington' => 'Man on Fire'),
               
'Comedy' =>
                array (
'Charlie Chaplin' => 'City Lights',
                      
'Jim Carrey'    => 'Cable Guy',
                      
'Rowan Atkinson' => 'The Ultimate Disaster'));
$type_wanted = 'Action'; //You may switch type from Action to Comedy.
$hero_wanted = 'Pearce Brosnan'; // You may switch hero from Pearce Brosnan to Jim Carrey.

print ("$hero_wanted 's  $type_wanted movie is " . $movie_to_watch[$type_wanted][$hero_wanted].".");
// produces browser output as under:
// Pearce Brosnan 's Action movie is Die Another Day.
?>
Olegk, getmequick[at]gmail[dot]com
21-Aug-2007 03:59
Hey..

here is a function which helps to avoid using empty/isset
checkings for arrays.

(it's acts simillar to 'default' modifier in Smarty)

Using this function you will avoid 'Undefined index' or
'Undefined offset' error.

<?php

$_POST
['id']['other'] = 'val1';

/*
key exist (same as $_POST['id'][other])
*/
echo getRequestParam('id[other]', 'default value');

/*
key doesn't exist, we get default value (same as $_POST['var'])
*/

echo getRequestParam('var', 'default value');

function
getRequestParam( $var, $default = '', $method = 'post' )
{
   
preg_match_all('!(\w+)!i',$var, $match );
   
array_shift($match);
   
$_vars = $match[0];
   
$ret = null;   
   
    if(    
strtoupper($method)   ==  'POST' ) {
       
$ret = _findRequestParam($_vars, $_POST);
    }
    elseif(
strtoupper($method) == 'GET' ) {
       
$ret = _findRequestParam($_vars, $_GET);
    }
    elseif(
strtoupper($method) == 'COOKIE' ) {
       
$ret = _findRequestParam($_vars, $_COOKIE);
   
    }
    elseif(
strtoupper($method) == 'SESSION' ) {
       
$ret = _findRequestParam($_vars, $_SESSION);
    }   
   
    if (!
$ret )
          return
$default;
    else
        return
$ret;       
   
}

/**
@access private
*/

function _findRequestParam($vars, $find_in , $curr_key = 0)
{
    static
$ret;
   
    if(
array_key_exists($vars[$curr_key], $find_in) ) {
        if(
count( $vars)-1 == $curr_key ) {
           
$ret $find_in[$vars[$curr_key]];
        }
        elseif(
$curr_key < count( $vars)-1 ) {
           
_findRequestParam( $vars, $find_in[$vars[$curr_key]], $curr_key+);       
        }   
    }

    return
$ret;

}

?>

Hope this will help someone!
conorj
14-Jul-2007 09:34
Another note on unquoted array indices. Because it is first interpreted as a constant, it must obey the naming convention of constants. i.e. a letter or underscore followed by optional letter, digit and/or underscore characters.

Therefore while the following array declaration is legal:
$a = array('1st'=>'First','2nd'=>'Second');

Trying to access either array item as follows causes an error:

$first = "$a[1st]";
$second = "$a[2nd]";
moehbass at gmail dot com
10-Jul-2007 06:41
<b>Mark Gukov</b> wrote below:

Regarding the fact that there's no need to quote arrays keys when enclosed in double quotes: it only applies to single dimensional arrays.

The following works fine:

<?php
$r
['a'] = 'apple';
echo
"$r[a] is tasty.";
?>

...but in the case of multi-dimensional arrays:

<?php
$r
['a']['b'] = 'banana';
echo
"$r[a][b] is tasty.";
?>

would result in "Array[c] is tasty."
-----------------------------------------------------------------

However, the following runs fine;
$r['a']['b'] = 'banana';
echo "{$r[a][b]} is tasty.";

Just box it!
don dot hosek at gmail dot com
23-May-2007 06:37
It's slightly faster to use array_splice to remove an element of an array:
array_splice($array, $index, 1)
than to do it using the suggested method of unset and reindex:
unset($array[$index]);
$array = array_values($array);

The difference, however, is very small. With 950 iterations I had times of
unset and reindex: 0.22837495803833
splice: 0.22392416000366
lesantoso at yahoo dot com
20-Mar-2007 04:14
This Indonesian number speller function is twice
faster(*) than the one provided in class Terbilang by
anghuda(at)gmail(dot)com (25-May-2006 08:52):

http://www.lesantoso.com/terbilang.html

(*) 2.1 vs. 4.2 seconds in processing 10000 random numbers
Spudley
16-Mar-2007 03:44
On array recursion...

Given the following code:

<?
$myarray
= array('test',123);
$myarray[] = &$myarray;
print_r($myarray);
?>

The print_r() will display *RECURSION* when it gets to the third element of the array.

There doesn't appear to be any other way to scan an array for recursive references, so if you need to check for them, you'll have to use print_r() with its second parameter to capture the output and look for the word *RECURSION*.

It's not an elegant solution, but it's the only one I've found, so I hope it helps someone.
kal at kalunite dot com i mean dot net
16-Jan-2007 06:55
About the automatic conversion of bare strings...
My opinion is that it never should have been implemented. Isn't it easier to NOT implement this "handy" feature in the first place? It is such a convenient way for "smart" programmers to write unsafe, not-futureproof code. Please remove this feature from future versions of PHP, please. (Hey, if you could change the OOP mechanisms between PHP 4 and PHP 5, why can't you make this change, right?)
25-Oct-2006 10:18
This page should include details about how associative arrays are implemened inside PHP; e.g. using hash-maps or b-trees.

This has important implictions on the permance characteristics of associative arrays and how they should be used; e.g. b-tree are slow to insert but handle collisions better than hashmaps.  Hashmaps are faster if there are no collisions, but are slower to retrieve when there are collisions.  These factors have implictions on how associative arrays should be used.
Mark Gukov
27-Sep-2006 03:18
Regarding the fact that there's no need to quote arrays keys when enclosed in double quotes: it only applies to single dimensional arrays.

The following works fine:

<?php
$r
['a'] = 'apple';
echo
"$r[a] is tasty.";
?>

...but in the case of multi-dimensional arrays:

<?php
$r
['a']['b'] = 'banana';
echo
"$r[a][b] is tasty.";
?>

would result in "Array[c] is tasty."
petruzanautico at yahoo dot com dot ar
21-Sep-2006 09:30
Regarding the message of phoenixbytes:

The line foreach($bad as $baddies); will just yield in $baddies the last value of the array $bad.
I think that wasn't your intention, in that case there are faster and better ways than foreach.

I think what you wanted to do is:
<?php
foreach($bad as $baddies) // make a collection
{
    if (
preg_match("/$baddies/i", $mailto)) // find a match
   
{
   
$addrmail = "false";
    }
    else
    {
   
$addrmail = "true";
    }
}
// foreach end
?>
php dot net at todandlorna dot com
25-Jul-2006 05:28
in response to ch dot martin at gmail dot com

If you are using the following code:

<?php
$r
= array('05' => "abc", '35' => "def");
foreach (
$r as $key=>$value)
  
var_dump($key);
?>

and you need the array key '35' to be a string (for looping maybe), you can make sure the key is a string by appending a 0 on the front.

'035' instead of '35'
ch dot martin at gmail dot com
09-Jun-2006 12:40
Extremely irritating quirk regarding the variable types of array keys:

<?php
$r
= array('05' => "abc", '35' => "def");
foreach (
$r as $key=>$value)
   
var_dump($key);
?>

The first var_dump for '05' is:
    string(2) "05"
as expected.  But the second, '35', turns out as:
    int(35)

Php apparently decided to make the 35 became an int, but not the 05 (presumably because it leads with a zero).  As far as I can see, there is absolutely no way of making string(2) "35" an array key.
anghuda(at)gmail(dot)com
25-May-2006 07:52
this is simpler tha function display_angka_bilangan by ktaufik(at)gmail(dot)com (16-Feb-2005 12:40)

<?

/*
*
* Class : Terbilang
* Spell quantity numbers in Indonesian or Malay Language
*
*
* author: huda m elmatsani
* 21 September 2004
* freeware
*
* example:
* $bilangan = new Terbilang;
* echo $bilangan -> eja(137);
* result: seratus tiga puluh tujuh
*
*
*/

Class Terbilang {

    function
terbilang() {
       
$this->dasar = array(1=>'satu','dua','tiga','empat','lima','enam',
       
'tujuh','delapan','sembilan');

       
$this->angka = array(1000000000,1000000,1000,100,10,1);
       
$this->satuan = array('milyar','juta','ribu','ratus','puluh','');
    }

    function
eja($n) {

   
$i=0;
    while(
$n!=0){

       
$count = (int)($n/$this->angka[$i]);

        if(
$count>=10) $str .= $this->eja($count). " ".$this->satuan[$i]." ";
        else if(
$count > 0 && $count < 10)
           
$str .= $this->dasar[$count] . " ".$this->satuan[$i]." ";

           
$n -= $this->angka[$i] * $count;
           
$i++;
        }
       
$str = preg_replace("/satu puluh (\w+)/i","\\1 belas",$str);
       
$str = preg_replace("/satu (ribu|ratus|puluh|belas)/i","se\\1",$str);

        return
$str;
    }
}

?>
benjcarson at digitaljunkies dot ca
09-May-2006 02:46
phoenixbytes: The regex you have posted for matching email addresses is incorrect.  Among other things, it does not allow '+' before the '@' (which is perfectly valid and can be quite useful to separate extensions of a single address).  RFC 822 [1] defines the grammar for valid email addresses, and (the extemely long) regex implementing can be found at [2].  Even the "Add Note" page here at php.net says:

[quote]
And if you're posting an example of validating email addresses, please don't bother. Your example is almost certainly wrong for some small subset of cases. See this information from O'Reilly Mastering Regular Expressions book for the gory details.
[/quote]

A note to others: please do your homework before writing another email-matching regex.

[1] http://www.ietf.org/rfc/rfc0822.txt?number=822
[2] http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html.
phoenixbytes at o2 dot co dot uk
16-Apr-2006 06:10
i use the array() function for deciding upon an email address's validity, i have a 'wap stalker' of my site that loves to exploit every hole i leave, so i used the following script to avoid being email bombed with my own file sender script, the array() is used to filter out undesirable email providers and, of course, any and all of my own addresses. before all that i used a REGEX to make sure it's an actual email address before going any further.

$mailto = "mail.domain.org"; // the input to be tested

if (preg_match("/^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,6}$/i", $mailto)) // see if it's really an email address
{
    $bad = array('mytrashmail.com', 'mymail.ro', 'acasa.ro', 'gala.net', 'phoenixbytes'); // pick out the victims
    foreach($bad as $baddies); // make a collection

    if (preg_match("/$baddies/i", $mailto)) // find a match
    {
    $addrmail = "false";
    }
    else
    {
    $addrmail = "true";
    }

}
else
{
$addrmail = "false";
}

$addrmail can then be used in an argument.
$baddies can be used to give a list, if necessary.

i hope this helps someone.
crozzer
01-Apr-2006 01:54
Passing variables into the array constructor:
Just a NOOB pointer, I couldn't find other examples for this.  If you want to pass the value of an existing variable into the array() constructor, you can quote it or not, both methods are valid.

<?
$foo_value
= 'foo string';
$bar_value = 'bar string';

$myArray = array(
   
'foo_key' => $foo_value,     // not quoted
   
'bar_key' => "$bar_value");   // quoted

foreach ($myArray as $k => $v) {
   echo
"\$myArray[$k] => $v.<br />\n";
}
?>

Both of these will work as expected, but the unqoted $foo_value method above is marginally faster because adding quotes adds an additional string de-reference.
sales at maboom dot ch
13-Dec-2005 10:41
if you need to check a multidimensonal array for values it's handy to store it like

$ar['key1'][0]
$ar['key2'][0]
$ar['key3'][0]

$ar['key1'][1]
$ar['key2'][1]
$ar['key3'][1]

and to loop the keys.

Fill the array (from a database-request):

while($rf=mysql_fetch_row($rs))

{
    $nr=$rf[0];
    $channel['nr'][$nr]=$rf[1];
    $channel['chatter'][$nr]=$rf[2];
}

Call the values:

foreach(array_keys($channel['nr']) as $test)
{
print ' nr:'.$test.'<br>';
print 'value nr: '.$channel['nr'][$test].'<br>';
print ' chatter: '.$channel['chatter'][$test].'<br>';
}

This is useful, if you have to look later for an element
inside the array:

if(in_array($new_value,$channel['nr'])) print 'do something.';

Hope this helps someone.
ia [AT] zoznam [DOT] sk
30-Sep-2005 03:55
Regardin