KodeFor.Me
KodeFor.Me

Reputation: 13511

PHP | Array get both value and key

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?

Upvotes: 1

Views: 128

Answers (7)

ickmund
ickmund

Reputation: 289

echo array_keys($array['teamA'])[0];

Refer this for detailed information from official PHP site.

Upvotes: 2

Christoph Grimmer
Christoph Grimmer

Reputation: 4313

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.

Upvotes: 2

Dan
Dan

Reputation: 548

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.

Upvotes: 1

Peter Georgiev
Peter Georgiev

Reputation: 37

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.

Upvotes: 1

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

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

OR use key

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

Upvotes: 3

Bhavik Shah
Bhavik Shah

Reputation: 2291

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.

Upvotes: 2

Alvaro
Alvaro

Reputation: 41595

More simple:

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

More info

Upvotes: 5

Related Questions