Today I am learning php programming and I am dabbling with arrays, doing an exercise where I am asked to create an array and pass keys and values to that array and then display them. So far I have worked out this code, but I don't really understand how I could pass a key and a value with the method array_push
to a array
.
I attach my code block
// Crear una función la cual agregue un array con su respectiva clave y valor
function vehicle_sale ($aa,$ab,$ac,$ad){
$vehicle = [];
array_push($vehicle,$aa,$ab,$ac,$ad);
foreach($vehicle as $vehiculo => $cantidad){
echo "Los vehiculos son los siguientes: $vehiculo y la cantidad de venta dde este vehiculo es $cantidad <br>";
}
};
vehicle_sale('toyota','chevrolet','honda','wolsvangen');
You must first declare the array and then pass the properties or values to it, for example:
Then with the array_push you can put that vehicle in the list of vehicles:
You would only have to go through it with the Foreach.
I hope I have helped you, greetings.
One of the problems you have is that you are not clear about your data structure (the array) where the information is going to be stored.
On the other hand, you need 2 functions, one to record the sales and another to display the result.
In this proposal, the data is accumulated in the array
$vehicles
. In the functionvehicle_sale()
they are inserted into the array, if the value exists, the quantity is added to the existing one. See operator ??You will notice that the array is being passed as a reference
&array
, which connects$vehicles
to$array
and so there is no return. However if you don't want to work like that, you can usereturn $array;
Finally, the function
display_sales()
shows the sales of all vehicles, or one in particular if you specify it in the function.