Milos Sretin
Milos Sretin

Reputation: 1748

Slicing array and count

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

Answers (3)

nickb
nickb

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

Scott Yang
Scott Yang

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

John Conde
John Conde

Reputation: 219874

  1. Use a loop to counts the part you do want

  2. 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

Related Questions