Reputation: 143
Given the following arrays how can I elegantly validate that option, price and cost arrays have matching key values?
Array
(
[option] => Array
(
[1] => C
[2] => M
[3] => G
)
[price] => Array
(
[1] => 100
[2] => 200
[3] => 300
)
[cost] => Array
(
[1] => 0
[2] => 0
[3] => 0
)
)
I thought of running a foreach(array as key => values) on each array and sending those values to another array, and then using if(!in_array), but theres got to be a better way to do it.
Upvotes: 2
Views: 48
Reputation: 57
I recommend using an array in this way:
Array ( [option] => Array ( [C] => Array ( [price] => 100 [cost] => 0 ) [M] => Array ( [price] => 200 [cost] => 0 ) [G] => Array ( [price] => 300 [cost] => 0 ) ) )
PHP Code:
$product = array("option" => array("C" => array("price" => 100, "cost" => 0), "M" => array("price" => 200, "cost" => 0), "G" => array("price" => 300, "cost" => 0)));
Upvotes: 0
Reputation: 78994
It sounds like you want the same keys as there is no correlation with the values in the array. If so, you can run a diff on the keys of each sub-array:
if(call_user_func_array('array_diff_key', $array)) {
// not the same keys
} else {
// same keys
}
call_user_func_array()
takes the array as an array of arguments and passes each to array_diff_key()
Upvotes: 2