Jump to content


Photo

Array Question


  • Please log in to reply
2 replies to this topic

#1 Joe Haley

Joe Haley
  • Members
  • PipPipPip
  • Advanced Member
  • 103 posts
  • LocationCanada, eh?

Posted 19 July 2006 - 03:21 PM

Lets say i have a line of code:
$array[] = 'whatever';

Now lets say that i need the key of the element i just added to the array set to a variable or return.

How would i do this?
Give a man a fish; you have fed him for today.  Teach a man to fish; and you have fed him for a lifetime
Don't teach men to program. Teach them to fish.

Please, try the RTFM solution before asking for help:
http://php.net/manual/en/index.php

#2 GingerRobot

GingerRobot
  • Staff Alumni
  • Advanced Member
  • 4,086 posts
  • LocationUK

Posted 19 July 2006 - 03:31 PM

This is pretty much the example on the php website, but i wanted to try it out. The original is on here:
http://uk2.php.net/m...unction.key.php

<?php
$array[] = 'whatever';
while ($array_test = current($array)) {
   if ($array_test == 'whatever') {
       echo key($array);
   }
   next($array);
}
?>


#3 Joe Haley

Joe Haley
  • Members
  • PipPipPip
  • Advanced Member
  • 103 posts
  • LocationCanada, eh?

Posted 19 July 2006 - 03:40 PM

Seems a little... complex.

I did think of something, however:

$key = count($array);
if ($key != 0)
$key--;

$array[$key] = 'whatever';
return($key);

as it is just a numericly indexed array.


Edit:
ooohhh, key() is just what is needed!

$array[] = '';
end($array);
return key($array);

Give a man a fish; you have fed him for today.  Teach a man to fish; and you have fed him for a lifetime
Don't teach men to program. Teach them to fish.

Please, try the RTFM solution before asking for help:
http://php.net/manual/en/index.php




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users