简体   繁体   中英

Check if a particular array key is sequential in an array with mixed sequential and associative entries

Let's say I have an array like:

$array = [
    'value1',
    71,
    'stringKey' => 'value2',
    3 => 'value3',
    4 => 'value4',
    64 => 'value5',
    'value6',
];

I want to loop through the entries and do a different thing depending on whether the entry has a key "manually set" (eg, 64 => 'value5' ), or it's just a value with a "sequential" key (eg, 'value1' - which is actually 0 => 'value1' ).

foreach ($array as $key => $value) {
    if (/* $key has not been "manually set" (i.e., is "sequential") */) {
        $result[$value] = 'default';
    } else {
        $result[$key] = $value;
    }
}

So my resulting array would be:

[
    'value1' => 'default',
    71 => 'default',
    'stringKey' => 'value2',
    3 => 'value3',
    4 => 'value4',
    64 => 'value5',
    'value6' => 'default',
]

I have been trying with array_keys() , checking if is_numeric($key) , but nothing works for all the entries above.

I'm starting to think this is actually impossible...

You could do something like this:

$i = 0;
foreach($array as $key => $value) {
    if ($key == $i) {
        $result[$value] = 'default';
    } else {
        $result[$key] = $value;
    }
    if (is_integer($key) && $key >= $i) $i = (int)$key + 1;
}

However, it will treat 4 => 'value4' differently from what you had indicated, because the input array would be exactly the same if you would have put just 'value4' . There is no way to determine from the array whether you had explicitly mentioned the key 4 or omitted the key.

So the above code treats this key/value pair in the same way that it treats the last key/value pair.

The output is:

array (
  'value1' => 'default',
  71 => 'default',
  'stringKey' => 'value2',
  3 => 'value3',
  'value4' => 'default',
  64 => 'value5',
  'value6' => 'default',
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM