Php return key value pair

I need to return a key value pair from a function. It would be preferable to retain the structure of the data. I would like to avoid creating an array with only one value if possible as I do not care for the syntax key($result[0]) or an array with two values, as I would like something with a syntax or structure that suggests the key=>value relationship between the values. Is there a more elegant alternative to the array for returning multiple values from a function in php?

asked Dec 1, 2011 at 20:41

3

You can only use array(), really.

return array("key1" => "value1", "key2" => "value2");

Anything else would just be uglier or more confusing.

answered Dec 1, 2011 at 20:42

PolynomialPolynomial

26.9k11 gold badges79 silver badges107 bronze badges

1

How about:

function getData () {
  return array('key','value');
}

list($key,$value) = getData();
echo $key." = ".$value;

Although I must say, this sounds like a bizarrely specific and largely cosmetic requirement...

answered Dec 1, 2011 at 20:44

Php return key value pair

DaveRandomDaveRandom

86.8k11 gold badges149 silver badges173 bronze badges

3

Could you not return the values in an array, like so?

return array('key' => $key, 'value' => $value);

You could also do this:

return array($key => $value);

But that's involves more work to use after the fact, in my opinion.

answered Dec 1, 2011 at 20:44

Surreal DreamsSurreal Dreams

25.5k3 gold badges45 silver badges60 bronze badges

1

Return an array.

return array("key" => "value");

answered Dec 1, 2011 at 20:43

Php return key value pair

Madara's GhostMadara's Ghost

168k50 gold badges260 silver badges306 bronze badges

Here a full example proposed by @polynomial that might be interesting:

//Function declaration with a return of a key value pair array
function getUserRating(){
  return array(
    'rating' => $rating, 
    'average'  => $average
  );
}

// Retrieve one of the key value pair 
getUserRating()['rating'];
// Retrieve the other key value pair 
getUserRating()['average'];

Think this kind of magic only work with PHP 7 or further? OMG! It Works with PHP 5.4!

answered Feb 16, 2021 at 23:40

Php return key value pair

gtamborerogtamborero

2,47723 silver badges23 bronze badges

Am I misunderstanding your question, or do you not want return array('aKey' => 'aVal');?

answered Dec 1, 2011 at 20:43

Php return key value pair

simshaunsimshaun

21.1k1 gold badge56 silver badges73 bronze badges

3

(PHP 4, PHP 5, PHP 7, PHP 8)

keyFetch a key from an array

Description

key(array|object $array): int|string|null

Parameters

array

The array.

Return Values

The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns null.

Examples

Example #1 key() example

<?php
$array 
= array(
    
'fruit1' => 'apple',
    
'fruit2' => 'orange',
    
'fruit3' => 'grape',
    
'fruit4' => 'apple',
    
'fruit5' => 'apple');// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name current($array)) {
    if (
$fruit_name == 'apple') {
        echo 
key($array), "\n";
    }
    
next($array);
}
?>

The above example will output:

See Also

  • current() - Return the current element in an array
  • next() - Advance the internal pointer of an array
  • array_key_first() - Gets the first key of an array
  • foreach

lhardie

8 years ago

Note that using key($array) in a foreach loop may have unexpected results. 

When requiring the key inside a foreach loop, you should use:
foreach($array as $key => $value)

I was incorrectly using:
<?php
foreach($array as $value)
{
 
$mykey = key($array);
}
?>

and experiencing errors (the pointer of the array is already moved to the next item, so instead of getting the key for $value, you will get the key to the next value in the array)

CORRECT:
<?php
foreach($array as $key => $value)
{
 
$mykey = $key;
}
A noob error, but felt it might help someone else out there.

vinob44 at gmail dot com

8 years ago

Suppose if the array values are in numbers and numbers contains `0` then the loop will be terminated. To overcome this you can user like this

<?php
$array
= array(
   
'0' => '5',
   
'1' => '2',
   
'2' => '0',
   
'3' => '3',
   
'4' => '1');// wrong approachwhile ($fruit_name = current($array)) {

        echo

key($array).'<br />';
      
next($array);
}
// the way will be break loop when arra('2'=>0) because its value is '0', while(0) will terminate the loop

// correct approach

while ( ($fruit_name = current($array)) !== FALSE ) {

        echo

key($array).'<br />';
      
next($array);
}
//this will work properly
?>

FatBat

10 years ago

Needed to get the index of the max/highest value in an assoc array.
max() only returned the value, no index, so I did this instead.

<?php
reset
($x);   // optional.
arsort($x);
$key_of_max = key($x);   // returns the index.
?>

Md Tahazzot

2 years ago

(Editor note: Or just use the array_keys function)

Make as simple as possible but not simpler like this one :)

$k = array();
for($i = 0; $i < count($arr); $i++){
    $k[$i] = key($arr);
    next($arr);
}

danielmadsv at gmail dot com

3 years ago

In addition to FatBat's response, if you'd like to find out the highest key in an array (assoc or not) but don't want to arsort() it, take a look at this:

<?php

$arr

= [ '3' => 14, '1' => 15, '4' => 92, '15' => 65 ];$key_of_max = array_search( max($arr) , $arr);?>

What is array_keys () used for?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.

What is $Key in PHP?

Technical Details. Return Value: Returns the key of the array element that is currently being pointed to by the internal pointer. PHP Version: 4+

What is the use of array_flip () function?

The array_flip() function flips/exchanges all keys with their associated values in an array.

How do you find the key of an array?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.