I have a programming assignment to add values to a PHP array after I validate that their either ints, floats, or strings.
I need to take the contents of the $products
array and only insert them into the $inventory
array if the data meets those conditions.
This is my source array:
$products = [
[
'item_number' => 15678,
'description' => 'Tophat',
'size' => 'small',
'shelf' => 5,
'aisle' => 12,
'quantity' => 10,
'price' => 5.99
],
[
'item_number' => 15662,
'description' => 'T-shirt',
'size' => 'large',
'shelf' => 9,
'aisle' => 13,
'quantity' => 15,
'price' => null
]
];
This is my validation function:
{
foreach ($product as $value) {
if (!is_int($value) && !is_string($value) && !is_float($value)){
return false;
}
return true;
}
And this is the function that adds the $products
to the $inventory
array:
function create_inventory(array $products) : array
{
$inventory = [];
foreach ($products as $product)
{
if (is_valid($product)){
foreach ($product as $value) {
$inventory[] = $value;
}
}
}
return $inventory;
}
This works and only the Tophat
is added to the $inventory
array because the T-shirt
product has a null
value. The output looks like this:
0 : 15678
1 : Tophat
2 : small
3 : 5
4 : 12
5 : 10
6 : 5.99
But now I want to add the keys to the $inventory
array, not just the values. I would like the output from the $inventory
array to look like this:
item_number : 15678
description : Tophat
size : small
shelf : 5
aisle : 12
quantity : 10
price : $5.99
This is the full version of my script: store_inventory.php
I’ve tried a few things that haven’t worked. How can I add both the $key
and the $value
to the $inventory
array?
3
Answers
You need to pass the key along with the value:
Your validate function seems to never be called? It doesn’t even have a function name.
EDIT:
Since your products array is an array of arrays. This code will do what you want, without validation.
2nd EDIT:
You need to do something like this:
Or:
From how I understand the question I think It should be this way as it return the $inventory array with both the key and the value
As you can see in the comments, you can loop over an array keys and values using:
If there are no keys the index of the array is the key.
Now for you question, you can use this kind of loop to fill you
$inventory
. Another problem in your code is that if you have more than one valid product, it will override the previous valid product. In order to solve this, you could put all your valid products inside arrays in the inventory array. Here’s how:If you prefer, see this interactive example.