array_splice() - Numerical Offsets of Associative Arrays

Posted by Alix Axel on Stack Overflow See other posts from Stack Overflow or by Alix Axel
Published on 2010-05-08T23:07:52Z Indexed on 2010/05/08 23:18 UTC
Read the original article Hit count: 254

I'm trying to do something but I can't find any solution, I'm also having some trouble putting it into works so here is a sample code, maybe it'll be enough to demonstrate what I'm aiming for:

$input = array
(
    'who' => 'me',
    'what' => 'car',
    'more' => 'car',
    'when' => 'today',
);

Now, I want to use array_splice() to remove (and return) one element from the array:

$spliced = key(array_splice($input, 2, 1)); // I'm only interested in the key...

The above will remove and return 1 element (third argument) from $input (first argument), at offset 2 (second argument), so $spliced will hold the value more.

I'll be iterating over $input with a foreach loop, I know the key to be spliced but the problem is I don't know its numerical offset and since array_splice only accepts integers I don't know what to do.

A very dull example:

$result = array();

foreach ($input as $key => $value)
{
    if ($key == 'more')
    {
        // Remove the index "more" from $input and add it to $result.
        $result[] = key(array_splice($input, 2 /* How do I know its 2? */, 1));
    }
}

I first though of using array_search() but it's pointless since it'll return the associative index....

How do I determine the numerical offset of a associative index?

© Stack Overflow or respective owner

Related posts about php

Related posts about arrays