...

View Full Version : How to get index of array?



john6
10-19-2012, 10:27 AM
$myarray = array("one" => "ONE","two" => "TWO");

foreach($myarray as $position => $value){
echo index_version_of($position);
}


Is there any way to get the numerical index of $position?

i.e. instead of "one" get "1"?

patryk
10-19-2012, 10:35 AM
how about just calling your variables like $something[1] instead of $something['one'] ?

john6
10-19-2012, 11:06 AM
I need to have strings in both of them.

I know the example I posted looks useless, but I need the concept of that. :(

Inigoesdr
10-19-2012, 03:19 PM
You can do it this way:

$myarray = array("one" => "ONE","two" => "TWO");
foreach($myarray as $position => $value)
{
echo array_search($position, array_keys($myarray));
}
But if you just want the position then use a counter like this:

$myarray = array("one" => "ONE","two" => "TWO");

$i = 0;
foreach($myarray as $position => $value)
{
echo $i;
$i++;
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum