Emil Østervig Emil Østervig - 1 month ago 10
PHP Question

make array of part of other array in php

So I'm working on collecting a lot of data from a Gravity Forms form, which stores the values in array called $entry[].

I need to gather all the values from $entry[14] through $entry[30] or something around that. Is there a way to do a foreach loop or something for only those selected parts of the array?

my current solution is rather repetitive.

$valuesArray = array($entry["14"], $entry["15"], $entry["16"], $entry["17"], $entry["18"], $entry["19"]);


Var dump of $entry gives the following

array(30) {
["id"]=> string(2) "48"
["form_id"]=> string(1) "1"
["date_created"]=> string(19) "2016-10-27 13:30:24"
["is_starred"]=> int(0)
["is_read"]=> int(0)
["ip"]=> string(13) "..."
["source_url"]=> string(26) "http://examplesite.com/"
["post_id"]=> NULL
["currency"]=> string(3) "DKK"
["payment_status"]=> NULL
["payment_date"]=> NULL
["transaction_id"]=> NULL
["payment_amount"]=> NULL
["payment_method"]=> NULL
["is_fulfilled"]=> NULL
["created_by"]=> string(1) "1"
["transaction_type"]=> NULL
["user_agent"]=> string(82) ""
["status"]=> string(6) "active"
[9]=> string(14) "Jeg er en mand"
[10]=> string(9) "50-54 år"
[11]=> string(9) "Kommune 3"
[16]=> string(1) "3"
[15]=> string(1) "0"
[6]=> string(0) ""
[1]=> string(0) ""
[8]=> string(0) ""
[12]=> string(0) ""
[2]=> string(0) ""
[5]=> string(0) "" }

Answer

You could use a mix of functions, avoiding loops:

$keys = array_flip(range(14,30));
$result = array_intersect_key($entry, $keys);

range() generates an array with the indices you want to compare against.
array_flip() turns the so generated array values into array keys, since you want to intersect array keys.
array_intersect_key does what you need basically.

The above example could be written also as oneliner, but... you know readability and that ;)