-1

I have an array that looks like this

array:3 [
    0 => {
        "id": "1"
        "name": "Product 1"
        "price": "123"
    }
    1 => {
        "id": "2"
        "name": "Product 2"
        "price": "23"
    }
    2 => {
        "id": "3"
        "name": "Product 3"
        "price": "234"
    }
]

and I'm trying to find the max, min and the avg of the array. I'm not sure what I should look for or how I should do this

Aurilie
  • 189
  • 3
  • 14
  • Should we assume you mean the Max, Min and Avg of the `price` in this array? – RiggsFolly Feb 17 '21 at 12:27
  • You probably want to start with `array_column`. min and max are trivial after that, by using the functions of the same names, and how to calculate the average of an array of numbers, is something you should be able to easily research on your own. – CBroe Feb 17 '21 at 12:33
  • @RiggsFolly - sorry forgot to mention that but yes it's for the price – Aurilie Feb 17 '21 at 12:34
  • A similar [Q&A](https://stackoverflow.com/questions/5846156/get-min-and-max-value-in-php-array). – Zhorov Feb 17 '21 at 12:43

1 Answers1

1

Like pointed out in the comments, you can use array_column.

<?php

$arr = [
    0 => [
        "id"    => "1",
        "name"  => "Product 1",
        "price" => "123",
    ],
    1 => [
        "id"    => "2",
        "name"  => "Product 2",
        "price" => "23",
    ],
    2 => [
        "id"    => "3",
        "name"  => "Product 3",
        "price" => "234",
    ],
];

$prices = array_column($arr, 'price');
echo "minimum: " . min($prices) . "\n";
echo "maximum: " . max($prices) . "\n";
echo "average: " . (array_sum($prices) / count($arr)) . "\n";
Syscall
  • 19,327
  • 10
  • 37
  • 52
Harm Smits
  • 437
  • 3
  • 10