Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

target numeric keys only in array

Tags:

arrays

php

I have an array with 2 kinds of keys, strings and integers. I want to do foreach() on this array and want to do it for numeric keys only. What is the most elegant way of doing it?

like image 803
henrijs Avatar asked Oct 30 '11 21:10

henrijs


People also ask

How do you match a key in an array?

The array_intersect_key() function compares the keys of two (or more) arrays, and returns the matches. This function compares the keys of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

Can an array have keys?

No. Arrays can only have integers and strings as keys.

What is numeric array with example?

Numeric arrays allow us to store multiple values of the same data type in a single variable without having to create separate variables for each value. These values can then be accessed using an index which in case of numeric arrays is always a number. Note: By default the index always starts at zero.

Can array key be an array?

As array values can be other arrays, trees and multidimensional arrays are also possible. And : The key can either be an integer or a string.


2 Answers

Here's a complicated method using array_filter() to return the numeric keys then iterate over them.

// $input_array is your original array with numeric and string keys
// array_filter() returns an array of the numeric keys
// Use an anonymous function if logic beyond a simple built-in filtering function is needed
$numerickeys = array_filter(array_keys($input_array), function($k) {return is_int($k);});

// But in this simple case where the filter function is a plain
// built-in function requiring one argument, it can be passed as a string:
// Really, this is all that's needed:
$numerickeys = array_filter(array_keys($input_array), 'is_int');

foreach ($numerickeys as $key) {
  // do something with $input_array[$key']
}

It's much easier though to just foreach over everything:

foreach ($input_array as $key => $val) {
  if (is_int($key)) {
    // do stuff
  }
}

Edit Misread original post and thought I saw "numeric" rather than "integer" keys. Updated to use is_int() rather than is_numeric().

like image 95
Michael Berkowski Avatar answered Nov 15 '22 11:11

Michael Berkowski


    foreach($array as $key => $val) {
        if(!is_int($key))
             continue;
        // rest of the logic
    }
like image 35
Ehtesham Avatar answered Nov 15 '22 11:11

Ehtesham