简体   繁体   中英

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

Regards.

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);

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