Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the keys in a PHP Array by position?

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

like image 517
Richard77 Avatar asked Dec 01 '25 05:12

Richard77


1 Answers

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.

like image 134
hammus Avatar answered Dec 03 '25 22:12

hammus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!