Is there a way to specify getting all but the first element in an array? I generally use foreach() to loop through my arrays.
say array(1,2,3,4,5), i would only want 2, 3, 4 ,5 to show and for it to skip 1.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are multiple ways of approaching this problem.
The first solution is to use a flag boolean to indicate the first element and proceed in your
foreachIf your elements are naturally numerically indexed, you do not need the boolean flag, you can simply check if the key is 0.
The second way is to cheat your way into a naturally numerically indexed array if it isn’t already. I will use
array_keys()to get a naturally numerically indexed array of keys and loop it.The third way is to use the array internal pointer to skip the first element and then continue in a loop by using
reset(),next(),list(), andeach(). Performance and resource-wise, this is the best option. Maintainability suffers greatly though.If you don’t mind losing the first element of the array, you can
array_shift()it.You can also
array_slice()the array. I’m also usingcount()in order to be able to set thepreserve_keysparameter totrue.