0

I'm looking for a way to push values into an array with automatic incremented keys. The porblem: I want to know the key of the inserted value.

Is there a way to do this? Insert values into an array and get the index of the inserted value?

The count of the array is not equal to the next insert-key, when an item gets removed from the array.

Thanks Alex

1
  • Nope. If I unset a value in the array, the count doesn't match with the next insert-key. Commented May 23, 2018 at 7:35

3 Answers 3

0

A simple wrapper function around array_push() could help:

function array_push_autoinc(array &$array, $item) {
    $next = sizeof($array);
    $array[$next] = $item;
    return $next;
}
Sign up to request clarification or add additional context in comments.

1 Comment

In a CLI project I used this: $timers = array(); function addTimer($seconds){ static $c = -1; global $timers; $timers[ ++$c ]=$seconds; return $c; }
0

You can use end() just after array_push. You will get the last insterted element.

end() advances array 's internal pointer to the last element, and returns its value.

key() returns the index element of the current array position.

Please have a look at below example:

$array = array(
    '0' => 'one',
    '1' => 'two',
    '2' => 'three', 
);

end($array);         // move the pointer to the end of array
$key = key($array);  // fetches the key of the element by the pointer

var_dump($key);

You can try one more solution, that will be faster.

$last_key = key( array_slice( $array, -1, 1, TRUE ) );
echo $last_key; //output "last"

Hope this will help you.

Comments

0

I found a solution:

This is my example-array:

$array = [2 => "two", 1 => "one", "four" => 4];

As you can see, there are strings and integers used as array-keys.

First of all I need to sort the array by its keys:

ksort($array);

Now the array looks like this:

$array = ["four" => 4, 1 => "one", 2 => "two"];

Now I can move the pointer to the end of the array and get the key (so I have the highest numeric key):

end($array);
$key = key($array);

I now increase the key by 1 and insert the value with the new key:

$key++;
$array[$key] = "three";

Now the key is saved in the variable $key and the array looks like this:

$array = ["four" => 4, 1 => "one", 2 => "two", 3 => "three"];
$key = 3;

That's it.

Now the complete code for all of you script-kiddies out there:

$array = [2 => "two", 1 => "one", "four" => 4];

ksort($array);
end($array);
$key = key($array);
$key++;

$array[$key] = "three";

Comments