Hüseyin ASLIM
Hüseyin ASLIM

Reputation: 153

array_diff Array to string conversion in error

I want calculate different two array but i get error;

Notice:  Array to string conversion in x.php on line 255

And not calculate different.

Code:

            $db->where('lisansID', $_POST['licence']);
            $mActivation = $db->get('moduleactivation', null, 'modulID');
            $aktifler = Array();
            $gelenler = Array();
            foreach($mActivation as $key=>$val)
            {
                $aktifler[] =   $val;
            }

            foreach ($_POST['module'] as $key => $value) {
                $gelenler[] = $val;
            }
            echo '<pre>Aktifler: ';
            print_r($aktifler);
            echo '</pre>';
            echo '<pre> Gelenler:';
            print_r($gelenler);
            echo '</pre> Fark:';
///line 255: 
            var_dump(array_diff($aktifler, $gelenler));

Upvotes: 1

Views: 7567

Answers (2)

Fabian Schmengler
Fabian Schmengler

Reputation: 24576

array_diff can only compare strings or values that can be casted to (string). But the elements of $aktifler and $gelenler are arrays by themselves, that's why you get this notice (also, converting an array to string always results in the string "Array", so all arrays will be treated as equal).

See array_diff:

Note:

Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

Use array_udiff instead, where you can define your own comparison function.

$out = array_udiff($aktifler, $gelenler, function($a, $b) {
    // the callback must return 0 for equal values
    return intval($a != $b);
});

Upvotes: 7

Martin
Martin

Reputation: 22760

Try breaking the final part into steps.

  • Take the row,
  • Save the output,
  • display the output.

thus:

$out = array_diff($aktifler, $gelenler);
var_dump($out);

You have a typo in your code, on the second foreach the $value is not assigned to the array, which is instead given $val. That's your problem.

Also you should get into the habit of unset()ing values from the foreach loop once the loop has completed.

foreach($a as $b => $c){
...
}
unset($b,$c);

Upvotes: 0

Related Questions