Yogesh Saroya
Yogesh Saroya

Reputation: 1495

How to check is php array have different value of key

I have this array

Array
(
    [0] => Array
        (
            [id] => 1
            [job_id] => 100
        )
    [1] => Array
        (
            [id] => 2
            [job_id] => 100
        )
    [2] => Array
        (
            [id] => 3
            [job_id] => 101
        )
)

Now here how to check if "job_id" is different. eg all have same job_id or not and how many different job_id array have.

Thanks

Upvotes: 0

Views: 41

Answers (2)

pixx
pixx

Reputation: 107

Well, if it is not a too large array, you can do the following:

<?php

$arr = [
    ['id' => 1, 'job_id' => 100],
    ['id' => 2, 'job_id' => 100],
    ['id' => 3, 'job_id' => 101]
];

$jobids = array_unique(array_column($arr, 'job_id'));

var_dump($jobids);

This looks like a db-result, in wich case it would be better to use a group-by statement?

Upvotes: 1

narayansharma91
narayansharma91

Reputation: 2353

Try this using array function:

$data = Array
(
[0] => Array
    (
        [id] => 1
        [job_id] => 100
    )
[1] => Array
    (
        [id] => 2
        [job_id] => 100
    )
[2] => Array
    (
        [id] => 3
        [job_id] => 101
    )
)
$totalDifferentJobId = count(array_unique(array_column($data, 'job_id')));

It will give you total unique job

Upvotes: 1

Related Questions