views:

185

answers:

2

I'm trying to add an extra class tag if an element / value is the first one found in an array. The problem is, I don't really know what the key will be...

A minified example of the array

Array (
    [0] => Array(
            id => 1
            name = Miller
            )
    [1] => Array(
                id => 4
                name = Miller
            )
    [2] => Array(
                id => 2
                name => Smith
    [3] => Array(
                id => 7
                name => Jones
            )
    [4] => Array(
                id => 9
                name => Smith
            )
)

So, if it's the first instance of "name", then I want to add a class.

+1  A: 

I think I sort of understand what you're trying to do. You could loop through the array and check each name. Keep the names you've already created a class for in a separate array.

for each element in this array
    if is in array 'done already' then: continue
    else:
        create the new class
        add name to the 'done already' array

Sorry for the pseudo-code, but it explains it fairly well.

Edit: here's the code for it...

$done = array();
foreach ($array as $item) {
    if (in_array($item['name'], $done)) continue;
    // It's the first, do something
    $done[] = $item['name'];
}
animuson
+1  A: 

I assume you're loop through this array. So, simple condition can be used

$first=0;
foreach ($arr as $value) {
  if (!$first++) echo "first class!";
  echo $value;
  // the rest of process.
}

To get just first value of an array you can also use old fashioned reset() and current() functions

reset($arr);
$first=current($arr);
Col. Shrapnel
This won't work. I don't want the first value in an array, I want the first element *per* name in an array.
andy787899
well add this name to the condition
Col. Shrapnel
if you want to mark each name's first appearance you have to record previuosly used names, into array.And check this array against each name.
Col. Shrapnel