-1

I have the following array:

$array = ('foo' => 'bar');

How do I echo 'foo' without using foreach or arraykeys?

TSR
  • 17,242
  • 27
  • 93
  • 197

1 Answers1

1

This is a duplicate question, but you've created the "artificial" construct of not being able to use array_keys for some reason, so I want to hilight the options without array_keys:

Note that many of the comments have you look for it by the value of foo, but I'm assuming you don't / cannot know the values of the array, so these methods do not rely on knowing anything about the array:

There's a few ways without array_keys. Here's just two:

Using reset and key:

reset( $array );
echo key( $array );

Or using array_flip:

$array = array_flip( $array );
echo reset( $array );

And, there's at least one way using array_keys:

$keys = array_keys( $array );
echo reset( $keys );

There are likely many other approaches.

Community
  • 1
  • 1
random_user_name
  • 25,694
  • 7
  • 76
  • 115