Rachmad
Rachmad

Reputation: 137

How can I access a specific value of a multidimensional array?

I am trying to access a specific value in a multidimensional array, but I am getting an undefined index error.

Here is my code :

     $hasil_ringkasan=array();
     foreach ($hasil_kelas as $key => $value) {
            $mayoritas = array_count_values($value);
            if($mayoritas['ringkasan']>1){
                array_push($hasil_ringkasan,$key);
            }

     }

Here is the output of $hasil_kelas :

Array
(
    [0] => Array
        (
            [0] => ringkasan
            [1] => ringkasan
            [2] => bukan
        )

    [1] => Array
        (
            [0] => ringkasan
            [1] => ringkasan
            [2] => ringkasan
        )

    [2] => Array
        (
            [0] => ringkasan
            [1] => ringkasan
            [2] => ringkasan
        )

)

But why when I run my first code is there an error "Message: Undefined index: ringkasan" even though the conditional is successfully executed?

My expected output like this :

Array(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 4
    [4] => 8
    [5] => 9
    [6] => 11
    [7] => 14
    [8] => 16
    [9] => 19
    [10] => 20
 )

Upvotes: 0

Views: 29

Answers (2)

JYoThI
JYoThI

Reputation: 12085

If any array is not have element ringkasan means it will through undefined errro so use isset to check

Example :

     `[0] => Array
    (
        [0] => bukan
        [1] => bukan
        [2] => bukan
    )`

In above example you will get

array(['bukan']=>3);  //so here is no ringkasan  key .

So use isset to check variable exists or not and then compare

if(isset($mayoritas['ringkasan']) && $mayoritas['ringkasan']>1)
{
    array_push($hasil_ringkasan,$key);
}

Upvotes: 1

RST
RST

Reputation: 3925

Test if ringkasan is present

 $hasil_ringkasan=array();
 foreach ($hasil_kelas as $key => $value) {
        $mayoritas = array_count_values($value);
        if(isset($mayoritas['ringkasan']) && $mayoritas['ringkasan']>1){
            array_push($hasil_ringkasan,$key);
        }

 }

Upvotes: 1

Related Questions