array_diff Array to string conversion in error - php

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));

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);
});

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);

Related

PHP - Elegantly extract the numeric indices in array a that are not in array b (not array_diff_key)

Suppose you have two arrays $a=array('apple','banana','canaple'); and $b=array('apple');, how do you (elegantly) extract the numeric indices of elements in array a that aren't in array b? (in this case, indices: 1 and 2).
In this case, array a will always have more elements than b.
Note, this is not asking for array_diff_key, but rather the numeric indices in the array with more elements that don't exist in the array with fewer elements.
array_diff gets you half way there. Using array_keys on the diff gets you the rest of what you want.
$a = ['apple','banana','canaple'];
$b = ['apple'];
$diff = array_diff($a, $b);
$keys = array_keys($diff);
var_dump($keys); // [1, 2]
This is because array_diff returns both the element and it's key from the first array. If you wanted to write a PHP implementation of array_diff it might look something like this...
function array_diff(Array ... $arrays) {
$return = [];
$cmp = array_shift($arrays);
foreach ($cmp as $key => $value) {
foreach($arrays as $array) {
if (!in_array($value, $array)) {
$return[$key] = $value;
}
}
}
return $return;
}
This gives you an idea how you might achieve the result, but internally php implements this as a sort, because it's much faster than the aforementioned implementation.

How to find matching values in multidimentional arrays in PHP

I am wondering if anyone could possibly help?....I am trying to find the matching values in two multidimensional arrays (if any) and also return a boolean if matches exist or not. I got this working with 1D arrays, but I keep getting an array to string conversion error for $result = array_intersect($array1, $array2); and echo "$result [0]"; when I try it with 2d arrays.
// matching values in two 2d arrays?
$array1 = array (array ('A8'), array (9,6,3,4));
$array2 = array (array ('A14'), array (9, 6, 7,8));
$result = array_intersect($array1, $array2);
if ($result){
$match = true;
echo "$result [0]";
}
else{
$match = false;
}
if ($match === true){
//Do something
}
else {
//do something else
}
The PHP documentation for array_intersect states:
Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
So, the array to string conversion notice is occurring when PHP attempts to compare the array elements. In spite of the notice, PHP will actually convert each of the sub-arrays to a string. It is the string "Array". This means that because
array_intersect() returns an array containing all the values of array1 that are present in all the arguments.
you will end up with a $result containing every element in $array1, and a lot of notices.
How to fix this depends on exactly where/how you want to find matches.
If you just want to match any value anywhere in either of the arrays, you can just flatten them both into 1D arrays, and compare those with array_intersect.
array_walk_recursive($array1, function ($val) use (&$flat1) {
$flat1[] = $val;
});
array_walk_recursive($array2, function ($val) use (&$flat2) {
$flat2[] = $val;
});
$result = array_intersect($flat1, $flat2);
If the location of the matches in the arrays is important, the comparison will obviously need be more complex.
This error(PHP error: Array to string conversion) was caused by array_intersect($array1, $array2), cause this function will compare every single element of the two arrays.
In your situation, it will consider the comparison as this: (string)array ('A8') == (string)array ('A14'). But there isn't toString() method in array, so it will incur the error.
So, if you want to find the matching values in two multidimensional arrays, you must define your own function to find it.

Array_merge versus + [duplicate]

This question already has answers here:
What's the difference between array_merge and array + array? [duplicate]
(9 answers)
Closed 7 years ago.
When I use array_merge() with associative arrays I get what I want, but when I use them with numerical key arrays the keys get changed.
With + the keys are preserved but it doesn't work with associative arrays.
I don't understand how this works, can anybody explain it to me?
Because both arrays are numerically-indexed, only the values in the first array will be used.
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.
http://php.net/manual/en/language.operators.array.php
array_merge() has slightly different behavior:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
http://php.net/manual/en/function.array-merge.php
These two operation are totally different.
array plus
Array plus operation treats all array as assoc array.
When key conflict during plus, left(previous) value will be kept
null + array() will raise fatal error
array_merge()
array_merge() works different with index-array and assoc-array.
If both parameters are index-array, array_merge() concat index-array values.
If not, the index-array will to convert to values array, and then convert to assoc array.
Now it got two assoc array and merge them together, when key conflict, right(last) value will be kept.
array_merge(null, array()) returns array() and got a warning said, parameter #1 is not an array.
I post the code below to make things clear.
function array_plus($a, $b){
$results = array();
foreach($a as $k=>$v) if(!isset($results[$k]))$results[$k] = $v;
foreach($b as $k=>$v) if(!isset($results[$k]))$results[$k] = $v;
return $results;
}
//----------------------------------------------------------------
function is_index($a){
$keys = array_keys($a);
foreach($keys as $key) {
$i = intval($key);
if("$key"!="$i") return false;
}
return true;
}
function array_merge($a, $b){
if(is_index($a)) $a = array_values($a);
if(is_index($b)) $b = array_values($b);
$results = array();
if(is_index($a) and is_index($b)){
foreach($a as $v) $results[] = $v;
foreach($b as $v) $results[] = $v;
}
else{
foreach($a as $k=>$v) $results[$k] = $v;
foreach($b as $k=>$v) $results[$k] = $v;
}
return $results;
}

array notation differences php

What is the difference in the following array notations: $arr[$key] = $value and $arr[] = $value, which is a better way ?
function test(){
$key = 0;
$a = array(1,2,3,4,5);
foreach($a as $value){
$a[$key] = $value;
$key++;
}
print_r($a);
}
versus
function test(){
$a = array(1,2,3,4,5);
foreach($a as $value){
$a[] = $value;
}
print_r($a);
}
They are different.
$a[] = 'foo';
Adds an element to the end of the array, creating a new key for it (and increasing the overall size of the array). This is the same as array_push($array, 'foo');
$key = 0;
$a[$key] = 'foo';
Sets the 0 element of the array to foo, it overwrites the value in that location... The overall size of the array stays the same... This is the same as $array = array_slice($array, 0, 1, 'foo'); (but don't use that syntax)...
In your specific case, they are doing 2 different things. The first test function will result in an array array(1,2,3,4,5), whereas the second one will result in array(1,2,3,4,5,1,2,3,4,5). [] always adds new elemements to the end.... [$key] always sets....
$arr[$key] = $value sets a specific key to a specific value.
$arr[] = $value adds a value on to the end of the array.
Neither is "better". They serve completely different roles. This is like comparing writing and drawing. You use a pen for both of them, but which you use depends on the circumstance.
One ($a[$key] = $value) youare specifying the $key where PHP will override that array entry if you use the same key twice.
The other ($a[] = $value) PHP is handling the keys itself and just adding the array entry using the next available key.
The whole thing that you are doing is a bit redundant though, as in the first example you are trying to loop through the array setting its values to itself. In the second example you are duplicating the array.
If you want to append an element to the array I would use
$arr[] = $value;
It is simpler and you get all the information on that line and don't have to know what $key is.

How to get the first item from an associative PHP array?

If I had an array like:
$array['foo'] = 400;
$array['bar'] = 'xyz';
And I wanted to get the first item out of that array without knowing the key for it, how would I do that? Is there a function for this?
reset() gives you the first value of the array if you have an element inside the array:
$value = reset($array);
It also gives you FALSE in case the array is empty.
PHP < 7.3
If you don't know enough about the array (you're not sure whether the first key is foo or bar) then the array might well also be, maybe, empty.
So it would be best to check, especially if there is the chance that the returned value might be the boolean FALSE:
$value = empty($arr) ? $default : reset($arr);
The above code uses reset and so has side effects (it resets the internal pointer of the array), so you might prefer using array_slice to quickly access a copy of the first element of the array:
$value = $default;
foreach(array_slice($arr, 0, 1) as $value);
Assuming you want to get both the key and the value separately, you need to add the fourth parameter to array_slice:
foreach(array_slice($arr, 0, 1, true) as $key => $value);
To get the first item as a pair (key => value):
$item = array_slice($arr, 0, 1, true);
Simple modification to get the last item, key and value separately:
foreach(array_slice($arr, -1, 1, true) as $key => $value);
performance
If the array is not really big, you don't actually need array_slice and can rather get a copy of the whole keys array, then get the first item:
$key = count($arr) ? array_keys($arr)[0] : null;
If you have a very big array, though, the call to array_keys will require significant time and memory more than array_slice (both functions walk the array, but the latter terminates as soon as it has gathered the required number of items - which is one).
A notable exception is when you have the first key which points to a very large and convoluted object. In that case array_slice will duplicate that first large object, while array_keys will only grab the keys.
PHP 7.3+
PHP 7.3 onwards implements array_key_first() as well as array_key_last(). These are explicitly provided to access first and last keys efficiently without resetting the array's internal state as a side effect.
So since PHP 7.3 the first value of $array may be accessed with
$array[array_key_first($array)];
You still had better check that the array is not empty though, or you will get an error:
$firstKey = array_key_first($array);
if (null === $firstKey) {
$value = "Array is empty"; // An error should be handled here
} else {
$value = $array[$firstKey];
}
Fake loop that breaks on the first iteration:
$key = $value = NULL;
foreach ($array as $key => $value) {
break;
}
echo "$key = $value\n";
Or use each() (warning: deprecated as of PHP 7.2.0):
reset($array);
list($key, $value) = each($array);
echo "$key = $value\n";
There's a few options. array_shift() will return the first element, but it will also remove the first element from the array.
$first = array_shift($array);
current() will return the value of the array that its internal memory pointer is pointing to, which is the first element by default.
$first = current($array);
If you want to make sure that it is pointing to the first element, you can always use reset().
reset($array);
$first = current($array);
another easy and simple way to do it use array_values
array_values($array)[0]
Just so that we have some other options: reset($arr); good enough if you're not trying to keep the array pointer in place, and with very large arrays it incurs an minimal amount of overhead. That said, there are some problems with it:
$arr = array(1,2);
current($arr); // 1
next($arr); // 2
current($arr); // 2
reset($arr); // 1
current($arr); // 1 !This was 2 before! We've changed the array's pointer.
The way to do this without changing the pointer:
$arr[reset(array_keys($arr))]; // OR
reset(array_values($arr));
The benefit of $arr[reset(array_keys($arr))]; is that it raises an warning if the array is actually empty.
Test if the a variable is an array before getting the first element. When dynamically creating the array if it is set to null you get an error.
For Example:
if(is_array($array))
{
reset($array);
$first = key($array);
}
We can do
$first = reset($array);
Instead of
reset($array);
$first = current($array);
As reset()
returns the first element of the array after reset;
You can make:
$values = array_values($array);
echo $values[0];
Use reset() function to get the first item out of that array without knowing the key for it like this.
$value = array('foo' => 400, 'bar' => 'xyz');
echo reset($value);
output //
400
Starting with PHP 7.3.0 it's possible to do without resetting the internal pointer. You would use array_key_first. If you're sure that your array has values it in then you can just do:
$first = $array[array_key_first($array)];
More likely, you'll want to handle the case where the array is empty:
$first = (empty($array)) ? $default : $array[array_key_first($array)];
You can try this.
To get first value of the array :-
<?php
$large_array = array('foo' => 'bar', 'hello' => 'world');
var_dump(current($large_array));
?>
To get the first key of the array
<?php
$large_array = array('foo' => 'bar', 'hello' => 'world');
$large_array_keys = array_keys($large_array);
var_dump(array_shift($large_array_keys));
?>
In one line:
$array['foo'] = 400;
$array['bar'] = 'xyz';
echo 'First value= ' . $array[array_keys($array)[0]];
Expanded:
$keys = array_keys($array);
$key = $keys[0];
$value = $array[$key];
echo 'First value = ' . $value;
You could use array_values
$firstValue = array_values($array)[0];
You could use array_shift
I do this to get the first and last value. This works with more values too.
$a = array(
'foo' => 400,
'bar' => 'xyz',
);
$first = current($a); //400
$last = end($a); //xyz

Categories