How to Remove Numeric Keys in PHP Array?

This tutorial demonstrates how to remove numeric keys from a PHP array using the array_filter() function with is_string() and ARRAY_FILTER_USE_KEY. The provided code example illustrates the process, resulting in an array with only non-numeric keys. This tutorial enhances understanding of array manipulation in PHP.

How to Remove Numeric Keys in PHP Array?

Hello,

In this tutorial, I'll guide you through removing numeric keys from a PHP array with a simple example. You'll gain insights into the process of eliminating numeric keys from a PHP array, enhancing your understanding of array manipulation in PHP. This example provides a step-by-step explanation of how to delete numeric keys from an array in PHP, making it easy to follow along.

We'll utilize the array_filter() function along with is_string() and ARRAY_FILTER_USE_KEY to achieve this task effectively. Let's dive into the code snippet to see how it's done:

Example:

 $myArray = [1 => "One", "Two" => 2, 3 => "Three", "Four" => 4, 5 => "Five", "Six" => 6];
    
    $newArray = array_filter(
            $myArray,
            function ($k) { return is_string($k); },
            ARRAY_FILTER_USE_KEY
        );
    
    var_dump($newArray);

Output:

array(3) {
  ["Two"]=> int(2)
  ["Four"]=> int(4)
  ["Six"]=> int(6)
}

I hope this example helps you understand how to remove numeric keys from a PHP array effectively.