Reece Costello Reece Costello - 12 days ago 7
PHP Question

How can i return array values where key is greater than X

I am storing user messages in an array and i want to filter out the nonsense and store the valuable data in a log.

The array size is being generated by the user message which means the array can be any size depending on the size of the messsage.

So lets give an example

Say i have an array that looks like the following:

Array
(
[0] => some nonsense
[1] => some more nonsense
[2] => even more nonsense
[3] => valuable data
[4] => some more valuable data
[5] => even more valuable data
[6] => so much valuable data
)


We basically want to ignore array keys 0, 1 and 2 which leaves me with the data that i want so i can store it in a log file

My ideal logic in would be to
file_put_contents()
where array key is greater than 3.

Regards.

Answer

You can do this using array_slice:

array array_slice (
    array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]]
)

In your case, you should do:

$arr = array_slice($arr, 3);  // Gives you from [3], [4]... till the end.

For the offset parameter to be 3:

If offset is non-negative, the sequence will start at that offset in the array. If offset is negative, the sequence will start that far from the end of the array.

If you want to preserve the keys, you need to give another true at the end.

$arr = array_slice($arr, 3, null, true);