The other reply indicated the array_push
, but I would say it would be better (by being a language builder, 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? Wouldn’t it just be the case to use an operator to do such a thing?
Well, if you really need it, I would use a function, but instead of using the feedback, I would pass the 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 to the return of the function and thus can change the value of the array
of direct origin.
The function compact
sends the current scope variables with the names passed by parameter to a array
.
array &$array
indicates that the variable must be of the type array
and has to be an existing variable, which will be affected as reference within the function. To understand a little more, read on reference passage
Another curiosity: In PHP, after version 5.4, you don’t need to use the keyword array()
to declare them, you can use brackets...
Example:
$data = [
['nome' => 'nome', 'valor' => 'valor']
];
You want to create an array that serves as "database"?
– Lucas de Carvalho