The other answer indicated array_push
, but I would say that it would be better (for being a language constructor, not a function) and more readable to use empty brackets to add values.
Example:
$data = array(
array('name' => 'Jack', 'ano' => 2002, 'cidade' => 'SÃO PAULO')
);
$data[] = array('name' => 'Wallace', 'ano' => 1990', 'cidade' => 'Belo Horizonte');
The question I would ask is: Do you really need a function to do this? Would not it be just the case of using an operator to do such a thing?
Well, if you really need it, I would use a function, but instead of using the return, I would pass array
as a reference.
$array = [];
$array[] = ['nome' => 'Bacco', 'ano' => 1900, 'cidade' => 'Interior de SP'];
function adicionar(array &$array, $nome, $ano, $cidade) {
$array[] = compact('nome', 'ano', 'cidade');
}
adicionar($array, 'Wallace', 1990, 'BH');
Explanation:
-
When using the &
operator, you will not be held hostage by the function return, so you can change the value of the array
source directly.
-
The function compact
sends the variables of the current scope with the names passed by parameter to a array
.
-
array &$array
indicates that the variable must be of type array
and must be an already existing variable, which will be affected as a reference within the function. To understand a little more, read about passing by reference
Another curiosity: In PHP, after version 5.4, you do not need to use the keyword array()
to declare them, you can use brackets ...
Example:
$data = [
['nome' => 'nome', 'valor' => 'valor']
];