How to count elements inside array/object on PHP? - php

I have this array being sent to my view
Array
(
[0] => stdClass Object
(
[emg_id] => 2
[fkit] => 1
[door] =>
)
)
I would like to count how many elements are empty, NULL, or '0'.
I tried using count but it always returns '1', instead of counting all of the elements, so I can later determine which satisfy my conditions above.
Any ideas what I'm doing wrong?

// number of "null" elements
echo count(array_filter((array) $array[0], 'is_null'));
There are some other is_*()-functions built-in, that may help you for example to count the number of strings (and so on).
To test, if an element is (e.g.) 0, I suggest to use an anonymous function
echo count(array_filter((array) $array[0], function ($item) {
return $item === 0;
}));
The other cases are similar.

loop through them and count.
function loopMe($array, $value) {
$num = 0;
foreach($array as $key=>$val) {
if($val == $value)
$num++;
}
return $num;
}
$ar = array (
array (
"emg_id" => 2
"fkit" => 1
"door" => null));
$num = loopMe($ar[0], null);

Related

Remove duplicated values completely deleted from array in php

I want to remove the values from array which are same.
For example:
This is the array.
Array ( [0] => 1 [1] => 63 [2] => 1 )
is there any function or something in core php which return me only the value which is not duplicate i.e value with index number 1 and delete index 0 and 2, I want the result
Array ( [1] => 63)
Is there any way?
You can use array_filter() and array_count_values() to check the count is not greater then 1.
<?php
$data = [1, 63, 1];
$data = array_filter($data, function ($value) use ($data) {
return !(array_count_values($data)[$value] > 1);
});
print_r($data);
https://3v4l.org/uIVLN
Result:
Array
(
[1] => 63
)
Will also work fine with multiple dupes: https://3v4l.org/eJSTY
One option is to use array_count_values to count the values. Loop and push only the 1 values
$arr = array(1,63,1);
$arrKey = array_flip( $arr ); //Store the key
$result = array();
foreach( array_count_values($arr) as $k => $v ) {
if ( $v === 1 ) $result[ $arrKey[$k] ] = $k;
}
echo "<pre>";
print_r( $result );
echo "</pre>";
This will result to:
Array
(
[1] => 63
)
Doc: array_count_values
I believe that the best solution is the following:
function removeDuplicates(array $initialArray) : array
{
// Remove duplicate values from an array
$uniqueValues = array_unique($initialArray);
// Computes the difference of arrays with additional index check
$duplicateValues = array_diff_assoc($initialArray, $uniqueValues);
// Removed any values in both arrays
return array_diff($uniqueValues, $duplicateValues);
}
This solution utilises the following functions in PHP:
array_unique
array_diff_asoc
array_diff
You can use array_keys() with a search value as the second parameter to see how many times a value exists.
$array = [1, 63, 1, 12, 64, 12];
$new = [];
foreach ($array as $value) {
// Get all keys that have this value. If there's only one, save it.
if (count(array_keys($array, $value)) == 1) {
$new[] = $value;
}
}
Demo: https://3v4l.org/G1DCg
I don't know the performance of this compared to the other answers. I leave the profiling to someone else.

PHP Search multidimensional array for value & get corresponding element value

I am using PHP & I have a multi dimensional array which I need to search to see if the value of a "key" exists and if it does then get the value of the "field". Here's my array:
Array
(
[0] => Array
(
[key] => 31
[field] => CONSTRUCTN
[value] => LFD_CONSTRUCTION_2
)
[1] => Array
(
[key] => 32
[field] => COOLING
value] => LFD_COOLING_1
)
)
I want to be able to search the array for the "key" value of 31. If it exists, then I want to be able to extract the corresponding "field" value of "CONSTRUCTN".
I've tried using array_search(31, $myArray) but it does not work...
function searchMultiArray($val, $array) {
foreach ($array as $element) {
if ($element['key'] == $val) {
return $element['field'];
}
}
return null;
}
And then:
searchMultiArray(31, $myArray);
Should return "CONSTRUCTN".
One-line solution using array_column and array_search functions:
$result = array_search(31, array_column($arr, 'key', 'field'));
print_r($result); // CONSTRUCTN
Or with simple foreach loop:
$search_key = 31;
$result = "";
foreach ($arr as $item) { // $arr is your initial array
if ($item['key'] == $search_key) {
$result = $item['field'];
break;
}
}
print_r($result); // CONSTRUCTN
I haven't tested, but I think this should do it.
function searchByKey($value, $Array){
foreach ($Array as $innerArray) {
if ($innerArray['key'] == $value) {
return $innerArray['field'];
}
}
}
Then calling searchByKey(31, $myArray); should return 'CONSTRUCTN'.
One liner solution:
$result = is_numeric($res = array_search(31, array_column($myArray, 'key'))) ? $myArray[$res]["field"] : "";
array_search accepts 2 parameters i.e the value to be search and the array, subsequently I've provided the array which needs searching using array_column which gets that particular column from the array to be searched and is_numeric is used to make sure that valid key is returned so that result can displayed accordingly.

PHP Creating two dimensional arrays dependent on a function

I have an array like this:
[apple] => 11
[pear] => 5
[banana] => 3
[cucumber] => 2
[tomatoes] => 8
I would like to create multi-dimensional array like this:
[randomArrayName1]
[apple] => 11
[banana] => 3
[tomatoes] => 8
[randomArrayName2]
[pears] => 5
[cucumber] => 2
I wrote this below but it is not working and I have no clue how to make it do: what I need it to do
$quantity = array();
foreach($fruit as $key => $value) {
$quantity = Finder($key);
}
randomArrayName1 and randomArrayName2 will be generated depending on Finder() function's result. Depending on that result I want fruit array to be created as a second dimension array.
Solution:
The problem was that the function I wrote that created names like randomArrayName1, randomArrayName2... was in fact a XML function. Therefore, result of this function was not an array, it was XML simple object. This caused problem on creating multidimensional array. Once I implemented the code below it converted SimpleXML to Array and code worked fine.
$type is SimpleXML array
$out is result array
foreach ( (array) $type as $index => $node )
$out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;
You can use array_reduce. It takes three arguments, an initial array to operate on, a function which should operate on each element (which in turn requires two arguments, $carry, which is a variable that gets passed through to the function each time through the return statement, and $item, which is the array item being operated on) and finally an "initial" value for $carry within the function, which in this case is going to be our multidimensional array that gets eventually returned.
This is an example where the Finder function returns a key based on whether the value of the items in the array is odd or even, and sorts the values accordingly.
Note that we are operating on the array_keys of fruits, so that we have access to both key and value inside our reducer.
<?php
$fruit = ['apple' => 11, 'pear' => 5, 'banana' => 3, 'cucumber' => 2, 'tomatoes' => 8];
function Finder($fruit) {
return $fruit % 2 == 0 ? 'even' : 'odd';
}
$multi = array_reduce(array_keys($fruit), function($carry, $item) use ($fruit) {
$val = $fruit[$item];
$carry[Finder($val)][$item] = $val;
return $carry;
}, []);
var_dump($multi);
/* // output
array(2) {
["odd"]=>
array(3) {
["apple"]=>
int(11)
["pear"]=>
int(5)
["banana"]=>
int(3)
}
["even"]=>
array(2) {
["cucumber"]=>
int(2)
["tomatoes"]=>
int(8)
}
}
*/
You need to create the new index or access it if it has already been created and then create another element under that with the existing key and assign the value:
$quantity = array();
foreach($fruit as $key => $value) {
$quantity[Finder($key)][$key] = $value;
}
This is assuming that Finder() is returning a string like randomArrayName1.

How to compare 2 arrays for common items in PHP?

I am writing a script to compare the achievements of one player to another in a game. In each of the arrays the id and timestamp will match up on some entries. I have included a sample of one of the start of the 2 separate arrays:
Array
(
[0] => Array
(
[id] => 8213
[timestamp] => 1384420404000
[url] => http://www.wowhead.com/achievement=8213&who=Azramon&when=1384420404000
[name] => Friends In Places Higher Yet
)
[1] => Array
(
[id] => 6460
[timestamp] => 1384156380000
[url] => http://www.wowhead.com/achievement=6460&who=Azramon&when=1384156380000
[name] => Hydrophobia
)
I want to find all of the array items where the id and timestamp match. I have looked into array_intersect but I don't think this is what I am looking for as it will only find items when the entries are identical. Any help much appreciated.
You may use array_intersect_assoc function.
Try something like this:
<?php
$key_match = Array();
//Loop first array
foreach($array as $key => $element){
//Compare to second array
if($element == $array2[$key]){
//Store matching keys
$key_match[] = $key;
}
}
?>
$key_match will be an array with all matching keys.
(I'm at work and havn't had time to test the code)
Hope it helps
EDIT:
Fully working example below:
<?php
$a1["t"] = "123";
$a1["b"] = "124";
$a1["3"] = "125";
$a2["t"] = "123";
$a2["b"] = "124";
$a2["3"] = "115";
$key_match = Array();
//Loop first array
foreach($a1 as $key => $element){
//Compare to second array
if($element == $a2[$key]){
//Store matching keys
$key_match[] = $key;
}
}
var_dump($key_match);
?>
If you want to go on an exploration of array callback functions, take a look at array_uintersect. It's like array_intersect except you specify a function to use for the comparison. This means you can write your own.
Unfortunately, you need to implement a function that returns -1, 0 or 1 based on less than, same as, greater than, so you need more code. But I suspect that it'll be the most efficient way of doing what you're looking for.
function compareArrays( $compareArray1, $compareArray2 ) {
if ( $compareArray1['id'] == $compareArray2['id'] && $compareArray1['timestamp'] == $compareArray2['timestamp'] ) {
return 0;
}
if ( $compareArray1['id'] < $compareArray2['id'] ) {
return -1;
}
if ( $compareArray1['id'] > $compareArray2['id'] ) {
return 1;
}
if ( $compareArray1['timestamp'] < $compareArray2['timestamp'] ) {
return -1;
}
if ( $compareArray1['timestamp'] > $compareArray2['timestamp'] ) {
return 1;
}
}
var_dump( array_uintersect( $array1, $array2, "compareArrays") );

PHP - How can I find out if a value exists in an array when compared?

I have an array that looks like this:
Array
(
[0] => Array
(
[0] => 1
[id] => 1
)
[1] => Array
(
[0] => 2
[id] => 2
)
)
What I would like to do is compare an int value against what's in the id value field. So, if I were to pass in say a 1, I'd like to be able to have a function compare this. I was thinking in_array but I can't get that to work. Does anyone know what function I can use for this?
Thanks.
It's not entirely clear what you'd like the result of the function to be, however I'm guessing you'd like the key of array that contains the ID you are looking for, in that case the following function would find that.
<?php
function get_key($array, $id) {
foreach ($array as $key => $unit) {
if ($unit['id'] == $id) {
return $key;
}
}
}
Try something like this:
$needle = 1;
$found = false;
foreach ($array as $key => $val) {
if ($val['id'] === 1) {
$found = $key;
break;
}
}
if ($found !== false) {
echo 'found in $array['.$found.']';
}
Since you want something more compact:
$needle = 1;
array_filter($array, create_function('$val', 'return $val["id"] !== '.var_export($needle, true).';'))
That will filter out all those elements that’s id value is not 1.

Categories