Find empty array indexes function - php

I am checking array values empty or not like following:
Long format:
$empty = array();
foreach($array as $value)
if(empty($value)) $empty[] = $value;
Expected Function:
$empty = array_empty_values($array);
Is there any function like array_empty_values() that find empty array indexes?

If you want to check and remove the empty array element you can check this function in php array_filter()
array_filter accepts an array as input and removes all elements which are equal to null / 0 / flase

Use array_filter php built-in function
function filter_empty($var) {
return empty($var);
}
$result_array = array_filter($your_array, "filter_empty");
$your_array = array(1,'2','3',false,'');
$result_array = array_filter($your_array, "filter_empty");
echo print_r($result_array, true);
will print
Array
(
[3] =>
[4] =>
)
If you need only indexes you can use array_keys built-in function
echo print_r(array_keys($result_array), true);
that will print
Array
(
[0] => 3
[1] => 4
)

You need an array with the keys, not with the values. because the values are empty.
/**
* Get keys of empty array values
* #param array $array The array to check.
* #return array The keys of the empty values.
*/
array_empty_values($array) {
$empty = array();
foreach($array as $key => $value) {
if(empty($value)) {
$empty[] = $key;
}
}
return $empty;
}

Related

Build dynamic associative array from simple array in php

I have an array as given below
$arr = ['Product', 'Category', 'Rule'];
This can be a dynamic array meaning it can sometimes have between 1-5 elements inside it and its value can change.
How can we create an array as given below from the above one in a dynamic manner.
$json['Product']['Category']['Rule'] = 'fixed';
Simply put am just trying to make a multidimensional array from the values I get from the $arr.
This function should do it.
function nestArray($arr, $value) {
if (!count($arr)) {
return $value;
}
foreach (array_reverse($arr) as $key) {
$new = [$key => $value];
$value = $new;
}
return $new;
}
Example
$arr = ['Product', 'Category', 'Rule'];
$nested = nestArray($arr, 'fixed');
print_r($nested);
Output
Array
(
[Product] => Array
(
[Category] => Array
(
[Rule] => fixed
)
)
)

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.

Merging arrays recursively PHP

I am using this function two merge recursively arrays:
function array_merge_recursive_distinct(array &$array1, array &$array2) {
$merged = $array1;
foreach($array2 as $key => &$value) {
if(is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
$merged[$key] = array_merge_recursive_distinct($merged[$key], $value);
} else {
$merged[$key] = $value;
}
}
return $merged;
}
For using this function I am doing the following steps:
Declare an empty array $outArray = array();
Doing a while loop where I collect the information I need
During the while loop I call the array_merge_recursive_distinct function to fill the empty array recursively
However the final array contains only the last information it was gathered during the last while loop. I have tried to find a solution but I haven't succeed until now. What Am I doing wrong?
The recursive function takes all the info during the while loops (I have printed the input arrays in the recursive function) but it seems like it overwrites the merged array over and over again.
Thanks
CakePHP have a nice class called Hash, it implements a method called merge() who does exactly what you need
/**
* This function can be thought of as a hybrid between PHP's `array_merge` and `array_merge_recursive`.
*
* The difference between this method and the built-in ones, is that if an array key contains another array, then
* Hash::merge() will behave in a recursive fashion (unlike `array_merge`). But it will not act recursively for
* keys that contain scalar values (unlike `array_merge_recursive`).
*
* Note: This function will work with an unlimited amount of arguments and typecasts non-array parameters into arrays.
*
* #param array $data Array to be merged
* #param mixed $merge Array to merge with. The argument and all trailing arguments will be array cast when merged
* #return array Merged array
* #link http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::merge
*/
function merge_arrays_recursivelly(array $data, $merge) { // I changed the function name from merge to merge_arrays_recursivelly
$args = array_slice(func_get_args(), 1);
$return = $data;
foreach ($args as &$curArg) {
$stack[] = array((array) $curArg, &$return);
}
unset($curArg);
while (!empty($stack)) {
foreach ($stack as $curKey => &$curMerge) {
foreach ($curMerge[0] as $key => &$val) {
if (!empty($curMerge[1][$key]) && (array) $curMerge[1][$key] === $curMerge[1][$key] && (array) $val === $val) {
$stack[] = array(&$val, &$curMerge[1][$key]);
} elseif ((int) $key === $key && isset($curMerge[1][$key])) {
$curMerge[1][] = $val;
} else {
$curMerge[1][$key] = $val;
}
}
unset($stack[$curKey]);
}
unset($curMerge);
}
return $return;
}
https://book.cakephp.org/2.0/en/core-utility-libraries/hash.html#Hash::merge
Hash::merge source code
Perhaps something like this might be handy.
function array_merge_recursive_distinct(array &$array1, array &$array2) {
$merged = array_merge($array1,$array2);
asort($merged);
$merged = array_values(array_unique($merged));
return $merged;
}
$array1 = [];
$array2 = [1,2,3,4,5];
print_r(array_merge_recursive_distinct($array1,$array2));
$array1 = [1,2,3,6,12,19];
$array2 = [1,2,3,4,5];
print_r(array_merge_recursive_distinct($array1,$array2));
// output
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 12
[7] => 19
)
Test it on PHP Sandbox

PHP: Convert a standard array into associate array keys?

I'm working on a function that takes an array as a parameter, and then calls the value of a different associative array using the input array as keys. So for example,
array('level_1', 'level_2', 'level_3')
should become
$variable_defined_within_function['level_1']['level_2']['level_3']
I have a way to do this that I think will work, but it feels hacky and weird and I don't really want to use eval() unless I absolutely must.
function fetch($keys) {
if (!is_array($keys)) { $variable = array($keys); }
foreach ($keys as $key) {
$assoc_string .= '[' . str_replace('\'' . '\\\'' . $key) . ']';
}
$reqstring = 'if (isset($this->vars' . $assoc_string . ')) { return $this->vars' . $assoc_string . '; } else { return false; }';
eval($reqstring);
}
That just doesn't seem right, does it? How could I convert a list of keys into an associative array?
How about something like this:
function fetch($keys) {
if (!is_array($keys))
$keys = array($keys);
$arr = $this->vars;
foreach($keys as $key)
{
if (!isset($arr[$key]))
return FALSE;
$arr = $arr[$key];
}
return $arr;
}
Please consider this function as a starting point:
function fetch(array $keys, array $array) {
$pointer = &$array;
foreach ($keys as $key) {
if (!isset($pointer[$key]))
break;
$pointer = &$pointer[$key];
}
return $pointer;
}
it will loop through $array with provided $keys and return the value of the last existing key. You can use it as a base and add your logic for keys that not exists or something
Here is the solution, very simple, but yet, still very confusing sometimes.
$arr = array('level_1', 'level_2', 'level_3');
function fetch(array $array){
$numberOfDimensions = count($array);
// the value of array['level_1']['level_2']['level_3']
$value = "something";
for($i = $numberOfDimensions-1; $i >= 0; $i--){
$value = array($array[$i] => $value);
}
return $value;
}
print_r(fetch($arr));
Output:
Array ( [level_1] => Array ( [level_2] => Array ( [level_3] => something )))
As you can see, the solution is very simple, but to understand what is going on, you must understand how array works.
Every array has index, or hash when talking about associative arrays, and for each of those keys there is only exactly one value. The value can be of any type, so if we add an array as value of another array's element, you get 2-dimensional array. If you add 2-dimensional array as value of another arrays's element, you get 3-dimensional array. By repeating the process, you get N-dimensional array.
The algorithm works by going from the deepest key (the last element inside keys array) and assigning a new associative array to the $value variable, which is the value prepared to be set as array value of dimension above, all until the end of loop.
Lets have a look at the changes made to variable $value inside for loop, before and after change.
The initial value of variable $value is "something". "something" is value of array level_3, and so on...
So, running
print_r(array['level_1']['level_2']['level_3']);
will produce
something
Here is a full state view of the $value variable inside for loop:
Key: level_3
something
Array ( [level_3] => something )
Key: level_2
Array ( [level_3] => something )
Array ( [level_2] => Array ( [level_3] => something ) )
Key: level_1
Array ( [level_2] => Array ( [level_3] => something ) )
Array ( [level_1] => Array ( [level_2] => Array ( [level_3] => something ) ) )

return all keys of a associative array with a function

I have an associative array which looks like this:
Array (
[0] => Array ( )
[1] => Array ( )
[2] => Array ( [318] => 3.3333333333333 )
[3] => Array ( )
[4] => Array ( )
[5] => Array ( [317] => 5 )
)
I want to return all the array keys of the array as number, not string; thats why I am not echoing it. This is how I am trying:
function user_rated_posts(){
global $author;
if(isset($_GET['author_name'])) :
$curauth = get_userdatabylogin($author_name);
else :
$curauth = get_userdata(intval($author));
endif;
$user_rated_posts = get_user_meta($curauth->ID, 'plgn_rating',true);
foreach ($user_rated_posts as $arrs){
foreach($arrs as $key=> $value){
$keys= $key;
}
}
return $keys;
}
when I call the function like this:
array( explode(',',user_rated_posts()) )
I am only getting this
array(317)
I am trying to get all the keys in comma separated format, like:
array(318, 317)
Thanks.
You're overwriting the $keys variable each time you go through your loop, so it's always only set to the last one.
$keys = array();
foreach ($user_rated_posts as $arrs) {
foreach($arrs as $key=> $value){
$keys[] = $key;
}
}
return $keys;
... that will return an actual array structure, if you actually want a comma separated list then return implode(', ', $keys); instead.
You could use array_keys($array) instead of looping twice.
$keys = array();
foreach ($user_rated_posts as $arrs) {
$keys = array_merge($keys, array_keys($array));
}
return $keys;
I came up with a way that avoids the nested looping in favor of PHP's built in functions:
$result = array_map(array_keys,$user_rated_posts);
$result2 = array_map(implode, $result);
$result3 = array_filter($result2);
First line iterates over the array, returning the keys. Second line reduces the sub-array to strings. Third line removes the empty values.
Here is a working version: https://eval.in/99119
Added bonus: keeps the positions where the values were found as the keys like:
array(2) {
[2]=>
string(3) "318"
[5]=>
string(3) "317"
}

Categories