Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App
Next Article:
How to get form data using POST method in PHP ?
Next article icon

How to get specific key value from array in PHP ?

Last Updated : 04 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will see how to get specific key values from the given array. PHP array is a collection of items that are stored under keys. There are two possible types of keys: strings and integers. For any type of key, there is a common syntax to get a specific value by key — square brackets.

Example:

PHP
<?php  $mixedArr = [     10,     20,     'hello' => 'world',     30, ];  // Get a specific value by index $firstItem = $mixedArr[0]; echo "An item by index 0: {$firstItem}\n";  // Get a specific value by string key $stringItem = $mixedArr['hello']; echo "An item by key 'hello': {$stringItem}\n";  ?> 

Output
An item by index 0: 10 An item by key 'hello': world

Example 2: Sometimes we can accidentally try to get a non-existent item from the array. In this case, PHP throws a NOTICE. To avoid the issue, we have to check the key existence before accessing it. 

PHP
<?php  $arr = [1, 2, 3];  // Check the key existence with  // the built-in 'isset' function if (isset($arr[10])) {     echo "index 10 value is: {$arr[10]}\n"; } else {     echo "There are no value under the index 10\n"; }  $value = $arr[10] ?? 'unknown';  echo "A value under the index 10: {$value}\n";  ?> 

Output
There are no value under the index 10 A value under the index 10: unknown

Example 3: Using array_key_exists Function

The array_key_exists function is another way to check if a specific key exists in an array. This function checks if the given key or index exists in the array. Unlike isset, array_key_exists will return true even if the value associated with the key is null.

PHP
<?php $arr = ['a' => null, 'b' => 2]; // Nikunj Sonigara  // Check the key existence with // the built-in 'array_key_exists' function if (array_key_exists('a', $arr)) {     echo "The key 'a' exists in the array.\n"; } else {     echo "The key 'a' does not exist in the array.\n"; }  if (array_key_exists('c', $arr)) {     echo "The key 'c' exists in the array.\n"; } else {     echo "The key 'c' does not exist in the array.\n"; } ?> 

Output
The key 'a' exists in the array. The key 'c' does not exist in the array. 

Using isset()

In PHP, isset() checks if a variable is set and not null. To get a specific key's value from an array, use isset() to ensure the key exists before accessing its value, avoiding errors if the key is missing.

Example:

PHP
<?php $array = ["name" => "John", "age" => 25, "country" => "USA"]; $key = "age";  if (isset($array[$key])) {     echo $array[$key]; // Output: 25 } else {     echo "Key is not set"; } ?> 

Output
25

Using array_key_first and array_key_last Functions

The array_key_first function returns the first key of the given array without affecting the internal array pointer, while the array_key_last function returns the last key of the given array.

Example:

PHP
<?php  $mixedArr = [     10,     20,     'hello' => 'world',     30, ];  // Get the first key's value $firstKey = array_key_first($mixedArr); $firstValue = $mixedArr[$firstKey]; echo "First key's value: {$firstValue}\n";  // Get the last key's value $lastKey = array_key_last($mixedArr); $lastValue = $mixedArr[$lastKey]; echo "Last key's value: {$lastValue}\n";  ?> 

Output
First key's value: 10 Last key's value: 30




Next Article
How to get form data using POST method in PHP ?
author
forpelevin
Improve
Article Tags :
  • Web Technologies
  • PHP
  • PHP-function
  • PHP-Questions

Similar Reads

  • How to create an array with key value pairs in PHP?
    In PHP, an array with key-value pairs is called an associative array. It maps specific keys to values, allowing you to access elements using custom keys rather than numerical indices. Keys are strings or integers, while values can be of any data type. Here we have some common approaches to create an
    2 min read
  • How to get Values from HTML Input Array using JavaScript?
    This problem can be solved by using input tags having the same "name" attribute value that can group multiple values stored under one name which could later be accessed by using that name. Syntax let input = document.getElementsByName('array[]');What is an Input Array in HTML?An "input array" in HTM
    2 min read
  • How to get a variable name as a string in PHP?
    Use variable name as a string to get the variable name. There are many ways to solve this problem some of them are discussed below: Table of Content Using $GLOBALSUsing $$ OperatorUsing debug_backtrace()Using get_defined_vars() and array_search()Method 1: Using $GLOBALS: It is used to reference all
    3 min read
  • How to get the POST values from serializeArray in PHP ?
    When working with forms in web development, it's common to use JavaScript to serialize form data into a format that can be easily sent to the server. One popular method for serializing form data is using jQuery's serializeArray() function. However, once the data is serialized and sent to the server
    2 min read
  • How to get form data using POST method in PHP ?
    PHP provides a way to read raw POST data of an HTML Form using php:// which is used for accessing PHP’s input and output streams. In this article, we will use the mentioned way in three different ways. We will use php://input, which is a read-only PHP stream. We will create a basic HTML form page wh
    2 min read
  • How to check foreach Loop Key Value in PHP ?
    In PHP, the foreach loop can be used to loop over an array of elements. It can be used in many ways such as Table of Content Using the for-each loop with simple valuesUsing the foreach loop with Key-Value pairsUsing array_keys Function to Access Keys and ValuesUsing array_walk Function for Iteration
    3 min read
  • How to Populate Dropdown List with Array Values in PHP?
    We will create an array, and then populate the array elements to the dropdown list in PHP. It is a common task when you want to provide users with a selection of options. There are three approaches to achieve this, including using a foreach loop, array_map() function, and implode() function. Here, w
    2 min read
  • How to get cookies from curl into a variable in PHP ?
    The cURL standing for Client URL refers to a library for transferring data using various protocols supporting cookies, HTTP, FTP, IMAP, POP3, HTTPS (with SSL Certification), etc. This example will illustrate how to get cookies from a PHP cURL into a variable. The functions provide an option to set a
    2 min read
  • How to Get Multiple Selected Values of Select Box in PHP?
    Given a list of items, the task is to retrieve the multiple selected values from a select box in PHP. Use multiple attributes in HTML to select multiple values from drop-down list. Selecting multiple values in HTML depends on operating system and browsers.  For Windows users: hold down + CTRL key to
    2 min read
  • How to get total number of elements used in array in PHP ?
    In this article, we will discuss how to get total number of elements in PHP from an array. We can get total number of elements in an array by using count() and sizeof() functions. Using count() Function: The count() function is used to get the total number of elements in an array. Syntax: count(arra
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences