3

I have an array where I store key-value pair only when the value is not null. I'd like to know how to retrieve keys in the array?

  <?php
        $pArray = Array();

        if(!is_null($params['Name']))
            $pArray["Name"] = $params['Name'];

        if(!is_null($params['Age']))
            $pArray["Age"] = $params['Age'];

        if(!is_null($params['Salary']))
            $pArray["Salary"] = $params['Salary'];

        if(count($pArray) > 0)
        {
          //Loop through the array and get the key on by one ...                            
        }
  ?>

Thanks for helping

Rohit
  • 403
  • 3
  • 15
Richard77
  • 20,343
  • 46
  • 150
  • 252

4 Answers4

3

PHP's foreach loop has operators that allow you to loop over Key/Value pairs. Very handy:

foreach ($pArray as $key => $value)
{
    print $key
}

//if you wanted to just pick the first key i would do this: 

    foreach ($pArray as $key => $value)
{
    print $key;
    break;
}

An alternative to this approach is to call reset() and then key():

reset($pArray);
$first_key = key($pArray);

It's essentially the same as what is happening in the foreach(), but according to this answer there is a little less overhead.

Community
  • 1
  • 1
hammus
  • 2,602
  • 2
  • 19
  • 37
2

Why not just do:

foreach($pArray as $k=>$v){
   echo $k . ' - ' . $v . '<br>';
}

And you will be able to see the keys and their values at that point

MrTechie
  • 1,797
  • 4
  • 20
  • 36
2

array_keys function will return all the keys of an array.

Rohit
  • 403
  • 3
  • 15
2

To obtain the array keys:

$keys = array_keys($pArray);

To obtain the 1st key:

$key = $keys[0];

Reference : array_keys()

Raptor
  • 53,206
  • 45
  • 230
  • 366