Re: [PHP] Array difficulty



On 31/07/07, Alister Bulman <abulman@xxxxxxxxx> wrote:
On 31/07/07, Carlton Whitehead <carlton.whitehead@xxxxxxxxxxxx> wrote:
Couldn't you just do
arsort($chance);
$lastItem = chance[( count( $chance ) - 1 )];

I tried that earlier, but the problem is:
count( $chance ) - 1 ); returns an integer, so I would be asking for something like $chance[1] or $chance[0], neither of which exist in the array. Keep in mind $chance only has keys with string names:

http://uk3.php.net/current

$chance = array("lowercase" => 27, "uppercase" => 62, "integer" => 46);
arsort($chance);

max() returns the maximum value of an array.
array_search() finds the key for a value

So all that's needed to find the key of the maximum value is:

$result = array_search(max($chance), $chance);

I'd pretty much guarantee it'll be about an order of magnitude faster
than any solution that relies on sorting the array.

-robin
.



Relevant Pages

  • Re: A Fast sorting algorithm for almost sorted data
    ... far my compressor has potential but is nowhere near ready. ... It does however make heavy use of sorting. ... which I am currently calling Run sort. ... entire selected run can be added to the sorted output array. ...
    (comp.compression)
  • Re: Ranking Without Sorting
    ... >> sorting the elements of the array. ... > inverting and applying such a permutation can be done in linear time. ... > You can avoid having to sort the input array by treating the output ...
    (comp.programming)
  • Re: Ranking Without Sorting
    ... > sorting the elements of the array. ... inverting and applying such a permutation can be done in linear time. ... You can avoid having to sort the input array by treating the output ...
    (comp.programming)
  • Re: Ranking Without Sorting
    ... >> contradicted in my first post where I gave an example of how to rank ... > It seems quite clear to me that your 'ranking' array contains the exact ... An unsorted array contains the same information as the same array after sorting. ... > the same operation as the insertion loop in insertion sort... ...
    (comp.programming)
  • Re: Efficiently Extracting Identical Values From A List/Array
    ... struct SortHelper ... Now sort that array according to NodeIndex: ... running through the data structure and sorting things out. ...
    (comp.lang.cpp)