K
K
KorLagar2020-04-19 05:08:17
PHP
KorLagar, 2020-04-19 05:08:17

What is the solution to the problem associated with functions and arrays?

Good afternoon, please help me solve the problem in php: It is
necessary to create a function with any name, with one parameter - an array of positions in the basket.
The function should calculate and return how many items are in the cart (there can be several items in one item of the cart - the quantity field).
An array of the following structure will be passed to the function:
$basket = [
[
'position' => 'php book',
'quantity' => 1,
],
[
'position' => 'Wireless mouse',
'quantity' => 12 ,
]
];

The number of items in the basket can be from 0 to 10
At the same time, it is forbidden to use other functions, anonymous functions, type conversion, classes, global variables to solve the problem.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Loli E1ON, 2020-04-19
@KorLagar

<?php

function total($array = []): int {
    $total = 0;
    foreach ($array as &$value) {
        $total += $value['quantity'];
    }
    return $total;
}

echo total([
    [
    'position' => 'книга по php',
    'quantity' => 1,
    ],
    [
    'position' => 'Мышь беспроводная',
    'quantity' => 12,
    ]
]);

M
Mikhail Ushenin, 2020-04-19
@usheninmike

Use a loop foreach. With it, you don't need any of the above.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question