views:

38

answers:

2

In PHP when you have an associative array, e.g.:

$groups['paragraph'] = 3
$groups['line'] = 3

what is the syntax to access the first or second element of the array when you don't know the value of the keys?

Is there something like in a C# LINQ statement where you can say:

$mostFrequentGroup = $groups->first()?

or

$mostFrequentGroup = $groups->getElementWithIndex(0)?

Or do I have to use a foreach statement and pick them out as I do at the bottom of this code example:

//should return "paragraph"
echo getMostFrequentlyOccurringItem(array('line', 'paragraph', 'paragraph'));

//should return "line"
echo getMostFrequentlyOccurringItem(array('wholeNumber', 'date', 'date', 'line', 'line', 'line'));

//should return null
echo getMostFrequentlyOccurringItem(array('wholeNumber', 'wholeNumber', 'paragraph', 'paragraph'));

//should return "wholeNumber"
echo getMostFrequentlyOccurringItem(array('wholeNumber', '', '', ''));

function getMostFrequentlyOccurringItem($items) {

    //catch invalid entry
    if($items == null) {
        return null;
    }
    if(count($items) == 0) {
        return null;
    }

    //sort
    $groups = array_count_values($items);
    arsort($groups);

    //if there was a tie, then return null
    if($groups[0] == $groups[1]) { //******** HOW TO DO THIS? ***********
        return null;
    }

    //get most frequent
    $mostFrequentGroup = '';
    foreach($groups as $group => $numberOfTimesOccurrred) {
        if(trim($group) != '') {
            $mostFrequentGroup = $group;
            break;
        }
    }
    return $mostFrequentGroup;
}
+4  A: 

use these functions to set the internal array pointer:

http://ch.php.net/manual/en/function.reset.php

http://ch.php.net/manual/en/function.end.php

And this one to get the actual element: http://ch.php.net/manual/en/function.current.php

reset($groups);
echo current($groups); //the first one
end($groups);
echo current($groups); //the last one

If you wanna have the last/first key then just do something like $tmp = array_keys($groups); .

joni
of course, I can just do $groupNames = array_keys($groups), then I have $groupNames[0] and $groupNames[1], thanks.
Edward Tanguay
@Edward yeah, I was searching too far about this.
joni
A: 
$array = array('Alpha' => 1.1,'Bravo' => 2.2,'Charlie' => 3.3,'Delta' => 4.4,'Echo' =>5.5, 'Golf' => 6.6);

$pos = 3;

function getAtPos($tmpArray,$pos) {
 return array_splice($tmpArray,$pos-1,1);
}

$return = getAtPos($array,$pos);

var_dump($return);

OR

$array = array('Alpha' => 1.1,'Bravo' => 2.2,'Charlie' => 3.3,'Delta' => 4.4,'Echo' =>5.5, 'Golf' => 6.6);

$pos = 3;

function getAtPos($tmpArray,$pos) {
    $keys = array_keys($tmpArray);
    return array($keys[$pos-1] => $tmpArray[$keys[$pos-1]]);
}

$return = getAtPos($array,$pos);

var_dump($return);

EDIT

Assumes $pos = 1 for the first element, but easy to change for $pos = 0 by changing the $pos-1 references in the functions to $pos

Mark Baker