Arrays - nogsantos/study-zce-php-certification-codes GitHub Wiki

Array Basics

All arrays are ordered collections of items, called elements. Each element has a value, and is identified by a key that is unique to the array it belongs to.

Printing Arrays

PHP provides two functions that can be used to output a variable’s value recursively: print_r() and var_dump(). They differ in a few key points:

  • While both functions recursively print out the contents of composite value, only var_dump() outputs the data types of each value.
  • Only var_dump() is capable of outputting the value of more than one variable at the same time.
  • Only print_r can return its output as a string, as opposed to writing it to the script’s standard output.

Whether echo, var_dump() or print_r should be used in any one given scenario is, clearly, dependent on what you are trying to achieve. Generally speaking, echo will cover most of your bases, while var_dump() and print_r() offer a more specialized set of functionality that works well as an aid in debugging.

Enumerative vs. Associative

Arrays can be roughly divided in two categories: enumerative and associative. Enumerative arrays are indexed using only numerical indexes, while associative arrays (sometimes referred to as dictionaries) allow the association of an arbitrary key to every element.

Functions

range()
aceita dois inteiros como argumentos e retorna um array preenchido com todos os inteiros (inclusive) que estão entre argumentos.

<?php
$my_array = range(1,5);
//é equivalente a:
$my_array = array(1,2,3,4,5);
?>

list()
Assim como array(), não é exatamente uma função, e sim uma construção da própria linguagem. list() é usada para criar uma lista de variáveis em apenas uma operação.

<?php
$sql = "SELECT user_first, user_last, lst_log FROM users";
$result = mysql_query($sql);

while (list($first, $last, $last_login) = mysql_fetch_row($result)) {
echo "$last, $first - Last Login: $last_login";
}
?>

count()
Conta os elementos de um array, ou propriedades em um objeto.

isset() Verifica se a variável é definida.

<?php
$a = array ('a' => 1, 'b' => 2);
echo isset ($a['a']); // True
echo isset ($a['c']); // False
?>

However, isset() has the major drawback of considering an element whose value is NULL—which is perfectly valid—as inexistent:

<?php
$a = array ('a' => NULL, 'b' => 2);
echo isset ($a['a']); // False
?>

array_key_exists()
Checa se uma chave ou índice existe em um array

<?php
$a = array ('a' => NULL, 'b' => 2);
echo array_key_exists ('a', $a); // True
?>

in_array()
Checa se um valor existe em um array

<?php
$a = array ('a' => NULL, 'b' => 2);
echo in_array (2, $a); // True
?>

unset()
Destrói a variável especificada

<?php
$a = array ('a' => NULL, 'b' => 2);
unset ($a['b']);
echo in_array ($a, 2); // False
?>

array_combine(array $keys , array $values)
Cria um array usando os valores do array keys como chaves e os valores do array values como valores correspondentes.

<?php
$a = array('verde', 'vermelho', 'amarelo');
$b = array('abacate', 'maçã', 'banana');
$c = array_combine($a, $b);
print_r($c);
/*
output:
Array(
    [green]  => abacate
    [red]    => maçã
    [yellow] => banana
)
*/
?>

array_walk_recursive( array &$input , callback $funcname [, mixed $userdata ])
Aplica a função definida pelo usuário funcname para cada elemento do array input. Esta função irá ser usada em todo array.

<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
function test_print($item, $key){
    echo "$key holds $item\n";
}
array_walk_recursive($fruits, 'test_print');
/*
output:
a holds apple
b holds banana
sour holds lemon
*/
?>

each ( array $array )
Retorna o par chave/valor corrente de um array e avança o seu cursor Depois da execução de each(), o cursor interno do array vai apontar para o próximo elemento do array, ou após o último elemento se ele chegar ao final do array. Você deve usar reset() se quiser percorrer o array novamente.

<?php
$v = array(
    'a' => 'a1',
    'b' => 'a2',
    'c' => '',
    'd' => 'a3',
    'e' => '',
    'f' => 'a4',
    'g' => 'a5',
);
while($vc = each($v)) {
    echo $vc['value'];
}
?>

The Array Pointer

Each array has a pointer that indicates the “current” element of an array in an iteration. The pointer is used by a number of different constructs, but can only be manipulated through a set of functions and does not affect your ability to access individual elements of an array, nor is it affected by most “normal” array operations. The pointer is, in fact, a handy way of maintaining the iterative state of an array without needing an external variable to do the job for us. The most direct way of manipulating the pointer of an array is by using a series of functions designed specifically for this purpose. Upon starting an iteration over an array, the first step is usually to reset the pointer to its initial position using the reset() function; after that, we can move forward or backwards by one position by using prev() and next() respectively. At any given point, we can access the value of the current element using current() and its key using key().
Here’s an example:

<?php
$array = array('foo' => 'bar', 'baz', 'bat' => 2);
function displayArray(&$array) {
   reset($array);
   while (key($array) !== null) {
      echo key($array) .": " .current($array) . PHP_EOL;
      next($array);
   }
}
?>

Since you can iterate back-and-forth within an array by using its pointer, you could—in theory—start your iteration from the last element (using the end() function to reset the pointer to the bottom of the array) and then making your way to back the beginning:

<?php
$array = array (1, 2, 3);
end($array);
while (key ($array) !== null) {
   echo key($array) .": " .current($array) . PHP_EOL;
   prev($array);
}
?>

This only works because we are using a non-identity operator—using the inequality operator could cause some significant issues if one of the array’s elements has a key that evaluates to integer zero.