-1

I have the following array:

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

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

10
  • echo array_search('bar', $array) Commented Jan 20, 2017 at 16:20
  • 2
    echo reset(array_keys($array)); <- will output the FIRST key of ANY associative array. But, uses array_keys - why don't you want to use that? Commented Jan 20, 2017 at 16:21
  • @cale_b the question states: "without using foreach or arraykeys" Commented Jan 20, 2017 at 16:23
  • @TSR - Why do you want to avoid array_keys? Is this some sort of school homework or something? Commented Jan 20, 2017 at 16:23
  • print implode('',$array); echo $array['foo']; print array_shift($array); Commented Jan 20, 2017 at 16:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.