Reputation: 1748
How can I count the parts of array? For example:
Array:
[name] => Michael
[surname] => Hadfield
[midname] => Olsow
[email] => [email protected]
[phone] => 3342020
I want to count array fields excluding [midname] and [phone] so the result should be 3
And also I want to create array from this array with result:
[name] => Michael
[surname] => Hadfield
[email] => [email protected]
Is it possible?
Upvotes: 0
Views: 77
Reputation: 59709
You can try something like this:
$keys_to_exclude = array( 'midname', 'phone');
$new_array = array_diff_key( $original_array, array_flip( $keys_to_exclude));
echo count( $new_array);
print_r( $new_array);
With this input array:
$original_array = array(
'name' => 'Michael',
'surname' => 'Hadfield',
'midname' => 'Olsow',
'email' => '[email protected]',
'phone' => 3342020
);
You should get your desired output, that is, the echo count();
prints 3
and the resulting $new_array
is:
Array
(
[name] => Michael
[surname] => Hadfield
[email] => [email protected]
)
Upvotes: 1
Reputation: 2428
I guess you can always copy the array, unset the 2 indices, and then count it:
$array_copy = $array;
unset($array_copy('midname')); // Note unsetting a non-existent key does NOT throw an error.
unset($array_copy('phone'));
echo count($array_copy);
Upvotes: 0
Reputation: 219874
Use a loop to counts the part you do want
Multiply the result of count($array)
by .6 (assuming there is always five parts and three that you want to count)
$count = count($array) * .6;
Upvotes: 0