Page 1 of 1
Fetching the first element of an indexed array
Posted: Fri May 09, 2003 11:25 pm
by AVATAr
I have the following array:
Code: Select all
Array
(
ї17] => News
ї3] => Prod. Agroquímicos
ї1] => Prod. Farmaceuticos
ї2] => Prod. Veterniarios
)
I want to fetch the first element, in this case [17] => News, i need the index -> 17.
I make this function to resolve my problem:
Code: Select all
<?php
function first_Element($arr){
foreach ($arr as $k => $v){
return $k;
}
}
?>
but i dont think its the best solution, any comments?
thanks
Posted: Fri May 09, 2003 11:53 pm
by scorphus
Try this code:
reset() rewinds array's internal pointer to the first element and returns the value of the first array element.
This should work.
Regards,
Scorphus
Posted: Sat May 10, 2003 9:24 am
by AVATAr
ok i get it... thanks (legal!).
However, i need the key, so i implemented this (as its an indexed array):
PHP:
function first_Element($matriz){
return (array_search(reset($matriz),$matriz));
}
any suggestion?
Posted: Sun May 11, 2003 12:14 am
by scorphus
Take a look at the code below:
Code: Select all
<pre>
<?php
$anyArray = array(
17 => "News",
3 => "Prod. Agroquímicos",
1 => "Prod. Farmaceuticos",
2 => "Prod. Veterniarios");
echo key($anyArray) . " => ";
echo current($anyArray) . "\n";
next($anyArray);
echo key($anyArray) . " => ";
echo current($anyArray) . "\n";
echo reset($anyArray) . " (reseting the pointer to first element)\n";
echo key($anyArray) . " => ";
echo current($anyArray) . "\n";
?>
</pre>
The above code's output:
Code: Select all
17 => News
3 => Prod. Agroquímicos
News (reseting the pointer to first element)
17 => News
The
reset() function you already know.
key() returns the index of the current array element, which is returned by
current(). And
next() advance the internal array pointer to the next element.
I suggest you take a careful look at the Array Functions chapter of the PHP Manual located at
http://www.php.net/manual/en/ref.array.php. There you'll find a detailed documentation covering php array functions.
Regards,
Scorphus.
Posted: Sun May 11, 2003 12:32 am
by AVATAr
thanks scorphus... as you all can see... i found 3 solutions for the same problem... JEJE (if we want to solve something we have to use our imagination).
And the winner is:
Code: Select all
<?php
function firstElement($anyArray){
reset($anyArray);
return key($anyArray);
}
?>