1

I have a PHP array that looks like that:

$array = Array
(
    [teamA] => Array
    (
        [188555] => 1
    )
    [teamB] => Array
    (
        [188560] => 0
    )
    [status] => Array
    (
        [0] => on
    )
)

In the above example I can use the following code:

echo $array[teamA][188555];

to get the value 1.

The question now, is there a way to get the 188555 in similar way;

The keys teamA, teamB and status are always the same in the array. Alse both teamA and teamB arrays hold always only one record.

So is there a way to get only the key of the first element of the array teamA and teamB?

1
  • 3
    a bit offtopic: I just wanted to say that I think you should use $array['teamA'] instead of $array[teamA] as the latter works just because of a side effect (that undefined constants are treated as strings).. but 1) it generates a notice 2) who knows, maybe sometime you will define a constant teamA and you will have big problems in debugging Commented Feb 5, 2013 at 11:59

7 Answers 7

5

More simple:

echo key($array['teamA']);

More info

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

Comments

3
 foreach($array as $key=>$value)
 {
     foreach($value as $k=>$v)
     {
          echo $k;
      }
 }

OR use key

echo key($array['teamA']);

1 Comment

there is no any php function? Just I am asking for any function.
2
echo array_keys($array['teamA'])[0];

Refer this for detailed information from official PHP site.

Comments

2

Use two foreach

foreach($array as $key => $value){

    foreach($value as $key1 => $value2){
        echo $key1;
    }
}

This way, you can scale your application for future use also. If there will be more elements then also it would not break application.

Comments

2

You can use array_flip to exchange keys and values. So array('12345' => 'foo') becomes array('foo' => '12345').

Details about array_flip can be studied here.

Comments

1

I would suggest using list($key, $value) = each($array['teamA']) since the question was for both key and value. You won't be able to get the second or third value of the array without a loop though. You may have to reset the array first if you have changed its iterator in some way.

Comments

1

I suppose the simplest way to do this would be to use array_keys()?

So you'd do:

$teamAKey = array_shift(array_keys($array['TeamA'])); 
$teamBKey = array_shift(array_keys($array['TeamB']));

Obviously your approach would depend on how many times you intend to do it.
More info about array_keys and array_shift.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.