-1

How can I find the highest value in the sales key, for this case will be 21, using only "for loop"?

I have been trying to get the values for the sales index in order to find which sale had the highest value, however everything I do, its just simply to run all the array elements and show them into the screen.

$Vehicles = [
    "v1" => [
        "name" => "Audi",
        "model" => "2019",
        "sales" => 21
    ],
    "v2" => [
        "name" => "BMW",
        "model" => "2019",
        "sales" => 8
    ],
    "v3" => [
        "name" => "Aston Martin",
        "model" => "2019",
        "sales" => 7
    ]
];

The highest selling is 21. key = "sales" value = 21

khrzstoper
  • 41
  • 8
  • Please post one of your attempts to solve the problem. – jknotek Jul 04 '19 at 04:02
  • Possible duplicate of [How to Sort Multi-dimensional Array by Value?](https://stackoverflow.com/questions/2699086/how-to-sort-multi-dimensional-array-by-value) –  Jul 04 '19 at 04:16
  • since its an associative array, get the keys first, then use `for` – Kevin Jul 04 '19 at 04:33
  • and why on earth is it a requirement to just only use `for` loop, whats why there's a `foreach` – Kevin Jul 04 '19 at 04:34
  • Possible duplicate of [Find highest value in multidimensional array](https://stackoverflow.com/questions/17339421/find-highest-value-in-multidimensional-array) – Palak Jadav Jul 04 '19 at 04:58

2 Answers2

0

use array_column

max(array_column($Vehicles, 'sales'));
PHP Geek
  • 3,949
  • 1
  • 16
  • 32
0

Try This

Since PHP 5.5 there is array_column

array_column(array,column_key);

So, in your case to get max value -

$Highest_Selling_Value = max(array_column($Vehicles, 'sales'));

Rajendra Singh
  • 464
  • 3
  • 10
  • 1
    Yes, this is an easy answer, the problem is that it must be solved with pure for loop, it is an algorithm exercise. The reason is because I need to create a method inside a class and then pass a multidimensional array as a parameter and then find the highest value of an specific key value. – khrzstoper Jul 04 '19 at 11:11
  • if it works for you mark as the answer and upvote .@ChristianHernandez – Rajendra Singh Jul 04 '19 at 11:13