What is a key in php?

next → ← prev

The key( ) function returns the element key from the current internal pointer position. This function was introduced in 4.0.

Syntax

Parameter

ParameterDescriptionIs compulsory
array Specifies the array to use. compulsory

Returns

The key( ) returns the key of the array element that is currently being pointed by the internal pointer.

Example 1

Output:

The key from the current position is: 0

Example 2

Output:

Current position Key is : Subject1

Example 3

Output:

Current position Key is :tata

Example 4

Output:

The key from the current position is: 0


Next TopicPHP Array Functions

← prev next →

Help Others, Please Share

What is a key in php?
What is a key in php?
What is a key in php?


PHP arrays are actually ordered maps, meaning that all values of arrays have keys, and the items inside the array preserve order. When using arrays as simple lists as we have seen last chapter, a zero based counter is used to set the keys. Each item which is added to the array increments the next index by 1.

A good example for using arrays with keys is a phone book. Let's say we want to save the phone numbers of people in a class.

$phone_numbers = [
  "Alex" => "415-235-8573",
  "Jessica" => "415-492-4856",
];

print_r($phone_numbers);
echo "Alex's phone number is " . $phone_numbers["Alex"] . "\n";
echo "Jessica's phone number is " . $phone_numbers["Jessica"] . "\n";

To add an item to an array using a key, we use the brackets operator, as you would expect.

$phone_numbers = [
  "Alex" => "415-235-8573",
  "Jessica" => "415-492-4856",
];

$phone_numbers["Michael"] = "415-955-3857";

print_r($phone_numbers);

To check if a key exists within an array, we can use the array_key_exists function:

$phone_numbers = [
  "Alex" => "415-235-8573",
  "Jessica" => "415-492-4856",
];

if (array_key_exists("Alex", $phone_numbers)) {
    echo "Alex's phone number is " . $phone_numbers["Alex"] . "\n";
} else {
    echo "Alex's phone number is not in the phone book!";
}

if (array_key_exists("Michael", $phone_numbers)) {
    echo "Michael's phone number is " . $phone_numbers["Michael"] . "\n";
} else {
    echo "Michael's phone number is not in the phone book!";
}

If we want to extract only the keys of the array (the names), we can use the array_keys function.

$phone_numbers = [
  "Alex" => "415-235-8573",
  "Jessica" => "415-492-4856",
];

print_r(array_keys($phone_numbers));

Alternatively, to get only the values of an array (the phone numbers), we can use the array_values function.

$phone_numbers = [
  "Alex" => "415-235-8573",
  "Jessica" => "415-492-4856",
];

print_r(array_values($phone_numbers));

Exercise

Add a number to the phone book for Eric, with the number 415-874-7659, either by adding it to the array definition, or as a separate code line.

Last update on August 19 2022 21:51:14 (UTC/GMT +8 hours)

PHP: Return all the keys of an array

The array_keys() function is used to get all the keys or a subset of the keys of an array.

Version:

(PHP 4 and above)

Syntax:

array_keys(input_array, search_key_value, strict)

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.

Parameters:

Name DescriptionRequired /
Optional
Type
input_array Specified array. Required Array
search_key_value Value to be checked. Optional Array
strict As of PHP 5, this parameter determines if strict comparison (===) should be used during the search. Optional Boolean

Return value:

An array of all the keys of input_arrray.

Value Type: Array

Example - 1:

<?php
$array1=array("Orange" => 100, "Apple" => 200, "Banana" => 300, "Cherry" => 400);
print_r(array_keys($array1));
?> 

Output:

Array ( [0] => Orange [1] => Apple [2] => Banana [3] => Cherry )

Pictorial Presentation:

What is a key in php?

View the example in the browser

Example - 2 :

<?php
$array1=array("Orange","Apple","Banana","Apple");
print_r(array_keys($array1,"Apple"));
?>

Output :

Array ( [0] => 1 [1] => 3 )

View the example in the browser

Practice here online :

See also

PHP Function Reference

Previous:array_key_exists
Next: array_map

PHP: Tips of the Day

PHP: Can I try/catch a warning?

Set and restore error handler

One possibility is to set your own error handler before the call and restore the previous error handler later with restore_error_handler().

set_error_handler(function() { /* ignore errors */ });
dns_get_record();
restore_error_handler();

You could build on this idea and write a re-usable error handler that logs the errors for you.

set_error_handler([$logger, 'onSilencedError']);
dns_get_record();
restore_error_handler();

Turning errors into exceptions

You can use set_error_handler() and the ErrorException class to turn all php errors into exceptions.

set_error_handler(function($errno, $errstr, $errfile, $errline, $errcontext) {
    // error was suppressed with the @-operator
    if (0 === error_reporting()) {
        return false;
    }

    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});

try {
    dns_get_record();
} catch (ErrorException $e) {
    // ...
}

The important thing to note when using your own error handler is that it will bypass the error_reporting setting and pass all errors (notices, warnings, etc.) to your error handler. You can set a secondargument on set_error_handler() to define which error types you want to receive, or access the current setting using ... = error_reporting() inside the error handler.

Suppressing the warning

Another possibility is to suppress the call with the @ operator and check the return value of dns_get_record() afterwards. But I'd advise against this as errors/warnings are triggered to be handled, not to be suppressed.

Ref : https://bit.ly/36a5tyb

What do we mean by keys and values in PHP?

In the PHP code: $featured is the associative array being looped through, and as $key => $value means that each time the loop runs and selects a key-value pair from the array, it stores the key in the local $key variable to use inside the loop block and the value in the local $value variable.

How do I get keys in PHP?

If you have a value and want to find the key, use array_search() like this: $arr = array ('first' => 'a', 'second' => 'b', ); $key = array_search ('a', $arr); $key will now contain the key for value 'a' (that is, 'first' ).

What is key and value in array?

What are a key and value in an array? Keys are indexes and values are elements of an associative array. Associative arrays are basically objects in JavaScript where indexes are replaced by user-defined keys. They do not have a length property like a normal array and cannot be traversed using a normal for loop.

What is an array in PHP?

An array is a special variable that we use to store or hold more than one value in a single variable without having to create more variables to store those values. To create an array in PHP, we use the array function array( ) . By default, an array of any variable starts with the 0 index.