Array_splice () - Numeric offsets of associative arrays

I'm trying to do something, but I can’t find any solution, I also have problems with its operation, so here is an example code, maybe this will be enough to demonstrate what I am 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), therefore it $splicedwill hold the value more.

I will iterate $inputthrough the foreach loop, I know the key for splicing, but the problem is that I don’t know its numeric offset , and since array_spliceit only accepts integers, I don’t know what to do.

A very boring 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 used array_search()it at first , but this is pointless since it will return an associative index ....

How to determine the numerical offset of the associative index?

+1
source share
3 answers

Just capturing and unsetting the value is much better (and most likely faster) , but in any case, you can just count

$result = array();
$idx = 0; // init offset
foreach ($input as $key => $value)
{
    if ($key == 'more')
    {
        // Remove the index "more" from $input and add it to $result.
        $result[] = key(array_splice($input, $idx, 1));
    }
    $idx++; // count offset
}
print_R($result);
print_R($input);

gives

Array
(
    [0] => more
)
Array
(
    [who] => me
    [what] => car
    [when] => today
)

BUT Technically speaking, an associative key does not have a numeric index. If the input array was

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

2 "baz". array_slice , , , ( , ), .

, . $key === 'more', "" typecasted. , , "", . :

if(array_key_exists('more', $input)) unset($input['more']);
+4

:

$offset = array_search('more', array_keys($input)); // 2

"" , :

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

:

echo '<pre>';
print_r(array_keys($input));
echo '</pre>';

:

Array
(
    [0] => who
    [1] => what
    [2] => more
    [3] => when
    [4] => 0
    [5] => 1
    [6] => 2
)

, , .

. =)

+3
$i = 0;
foreach ($input as $key => $value)
{
    if ($key == 'more')
    {
        // Remove the index "more" from $input and add it to $result.
        $result[] = key(array_splice($input, $i , 1));

    }
    $i++;
}
+1

All Articles