0

In PHP I create an array of key value pairs like this, how to I get "mykey"?

$arr = array("mykey"=>"myvalue");

I know the code below will work, but I am interested to know if there is a language construct in PHP that allows me to this in a easier fashion.

foreach($arr as $key=>$value){
  $result = $key;
  break;
}
echo $result;

3 Answers 3

3

Just Use key if you dealing with one element and array_keys with arrays with multiple values.

Example

$arr = array("mykey"=>"myvalue");
var_dump(key($arr));

Or

 var_dump(array_keys($arr));

Output

string 'mykey' (length=5)

and

array
  0 => string 'mykey' (length=5)
Sign up to request clarification or add additional context in comments.

Comments

1

try this

you can use array_keys function in php

<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));

$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));

$array = array("color" => array("blue", "red", "green"),
               "size"  => array("small", "medium", "large"));
print_r(array_keys($array));
?>

Comments

0

you need to use array_keys, here's the manual

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.