PHP : How can I check Array in array? - php

I have 1 array, and the this array contains is an array also for each element. ex:
$arraycenter = array(
array('a','b','c','d'), //array1
array('e','d','f','g'), //array2
array('a','b','c','d'), //array3
array('e','d','f','g'), //array4
array(.............. ), //.....
array(...............); //array++
How can check array1 & array3 is the same, and array2 & array 4 is the same?

You can use the === operator:
if ($arraycenter[0] === $arraycenter[2] && $arraycenter[1] === $arraycenter[3]) {
// do stuff...
}

You can use array_diff
if (array_diff($arraycenter[1], $arraycenter[2], $arraycenter[3]))
// Do something
Or (if you don't know how many items need to be checked) you can use array_filter
$array_center = array_filter($array_center, function($value) use(&$array_center)
{
return array_diff($array_center[1], $value);
}

Related

How can you count the number keys in an array that have a non-empty corresponding value? [duplicate]

I can't seem to find a simple, straight-forward solution to the age-old problem of removing empty elements from arrays in PHP.
My input array may look like this:
Array ( [0] => Array ( [Name] => [EmailAddress] => ) )
(And so on, if there's more data, although there may not be...)
If it looks like the above, I want it to be completely empty after I've processed it.
So print_r($array); would output:
Array ( )
If I run $arrayX = array_filter($arrayX); I still get the same print_r output. Everywhere I've looked suggests this is the simplest way of removing empty array elements in PHP5, however.
I also tried $arrayX = array_filter($arrayX,'empty_array'); but I got the following error:
Warning: array_filter() [function.array-filter]: The second argument, 'empty_array', should be a valid callback
What am I doing wrong?
Try using array_map() to apply the filter to every array in $array:
$array = array_map('array_filter', $array);
$array = array_filter($array);
Demo: http://codepad.org/xfXEeApj
There are numerous examples of how to do this. You can try the docs, for one (see the first comment).
function array_filter_recursive($array, $callback = null) {
foreach ($array as $key => & $value) {
if (is_array($value)) {
$value = array_filter_recursive($value, $callback);
}
else {
if ( ! is_null($callback)) {
if ( ! $callback($value)) {
unset($array[$key]);
}
}
else {
if ( ! (bool) $value) {
unset($array[$key]);
}
}
}
}
unset($value);
return $array;
}
Granted this example doesn't actually use array_filter but you get the point.
The accepted answer does not do exactly what the OP asked. If you want to recursively remove ALL values that evaluate to false including empty arrays then use the following function:
function array_trim($input) {
return is_array($input) ? array_filter($input,
function (& $value) { return $value = array_trim($value); }
) : $input;
}
Or you could change the return condition according to your needs, for example:
{ return !is_array($value) or $value = array_trim($value); }
If you only want to remove empty arrays. Or you can change the condition to only test for "" or false or null, etc...
Following up jeremyharris' suggestion, this is how I needed to change it to make it work:
function array_filter_recursive($array) {
foreach ($array as $key => &$value) {
if (empty($value)) {
unset($array[$key]);
}
else {
if (is_array($value)) {
$value = array_filter_recursive($value);
if (empty($value)) {
unset($array[$key]);
}
}
}
}
return $array;
}
Try with:
$array = array_filter(array_map('array_filter', $array));
Example:
$array[0] = array(
'Name'=>'',
'EmailAddress'=>'',
);
print_r($array);
$array = array_filter(array_map('array_filter', $array));
print_r($array);
Output:
Array
(
[0] => Array
(
[Name] =>
[EmailAddress] =>
)
)
Array
(
)
array_filter() is not type-sensitive by default. This means that any zero-ish, false-y, null, empty values will be removed. My links to follow will demonstrate this point.
The OP's sample input array is 2-dimensional. If the data structure is static then recursion is not necessary. For anyone who would like to filter the zero-length values from a multi-dimensional array, I'll provide a static 2-dim method and a recursive method.
Static 2-dim Array:
This code performs a "zero-safe" filter on the 2nd level elements and then removes empty subarrays: (See this demo to see this method work with different (trickier) array data)
$array=[
['Name'=>'','EmailAddress'=>'']
];
var_export(
array_filter( // remove the 2nd level in the event that all subarray elements are removed
array_map( // access/iterate 2nd level values
function($v){
return array_filter($v,'strlen'); // filter out subarray elements with zero-length values
},$array // the input array
)
)
);
Here is the same code as a one-liner:
var_export(array_filter(array_map(function($v){return array_filter($v,'strlen');},$array)));
Output (as originally specified by the OP):
array (
)
*if you don't want to remove the empty subarrays, simply remove the outer array_filter() call.
Recursive method for multi-dimensional arrays of unknown depth: When the number of levels in an array are unknown, recursion is a logical technique. The following code will process each subarray, removing zero-length values and any empty subarrays as it goes. Here is a demo of this code with a few sample inputs.
$array=[
['Name'=>'','Array'=>['Keep'=>'Keep','Drop'=>['Drop2'=>'']],'EmailAddress'=>'','Pets'=>0,'Children'=>null],
['Name'=>'','EmailAddress'=>'','FavoriteNumber'=>'0']
];
function removeEmptyValuesAndSubarrays($array){
foreach($array as $k=>&$v){
if(is_array($v)){
$v=removeEmptyValuesAndSubarrays($v); // filter subarray and update array
if(!sizeof($v)){ // check array count
unset($array[$k]);
}
}elseif(!strlen($v)){ // this will handle (int) type values correctly
unset($array[$k]);
}
}
return $array;
}
var_export(removeEmptyValuesAndSubarrays($array));
Output:
array (
0 =>
array (
'Array' =>
array (
'Keep' => 'Keep',
),
'Pets' => 0,
),
1 =>
array (
'FavoriteNumber' => '0',
),
)
If anyone discovers an input array that breaks my recursive method, please post it (in its simplest form) as a comment and I'll update my answer.
When this question was asked, the latest version of PHP was 5.3.10. As of today, it is now 8.1.1, and a lot has changed since! Some of the earlier answers will provide unexpected results, due to changes in the core functionality. Therefore, I feel an up-to-date answer is required. The below will iterate through an array, remove any elements that are either an empty string, empty array, or null (so false and 0 will remain), and if this results in any more empty arrays, it will remove them too.
function removeEmptyArrayElements( $value ) {
if( is_array($value) ) {
$value = array_map('removeEmptyArrayElements', $value);
$value = array_filter( $value, function($v) {
// Change the below to determine which values get removed
return !( $v === "" || $v === null || (is_array($v) && empty($v)) );
} );
}
return $value;
}
To use it, you simply call removeEmptyArrayElements( $array );
If used inside class as helper method:
private function arrayFilterRecursive(array $array): array
{
foreach ($array as $key => &$value) {
if (empty($value)) {
unset($array[$key]);
} else if (is_array($value)) {
$value = self::arrayFilterRecursive($value);
}
}
return $array;
}

Check multiple values in array using array_intersect

I have this two arrays & two methods. $inputArray can be either only[1,2] or it can be[1,2,3,4].
$inputArray = [1,2];
$inputArray = [1,2,3,4];
$mainArray=[1,2,3,4,6,7,9];
$testObj->method1();
$testObj->method2();
Now need to execute method 1 only when there is no [1,2] in array.
I tried something like this but it fails for $inputArray.
if( count( $mainArray ) == count( array_intersect( $mainArray, $inputArray ) ) ) {
$testObj->method1();
} else {
$testObj->method2();
}
This is pseudocode.
Try in_array() function:
if(!in_array("1", $inputArray) && !in_array("2", $inputArray)) {
$testObj->method1();
}
How ever you question is confusing like
1. when you say you want to execute the method1 executed only when there is no [1,2] in array. so are you just point to specific 1 and 2 or count of 2 because 1 and 2 is also in the second array [1,2,3,4]
so in my mind as you are saying 3,4 is not in your desired array so i think below code will help you
<?php
$inputArray = [1,2];
//$inputArray = [1,2,3,4]; // uncomment the line and check your condition
$mainArray=[1,2,3,4,6,7,9];
// as in your desired array 3 and 4 is not so just check for that you can
// also use the condition like `in_array('3', $inputArray) || in_array('4', $inputArray)
if( in_array('3', $inputArray) ) {
echo "<br />Method 2";
} else {
echo "<br />Method 1";
}
?>
I hope this will solve the problem.
Your condition is always false. array_intersect() returns an array that contains the elements that are common to all its arguments. The result cannot be the largest array provided as argument. It is the smallest one or a subset of it.
The condition:
count(array_intersect($mainArray, $inputArray)) == count($inputArray)
is true when all the elements of $inputArray are present in $mainArray.
count(array_intersect($mainArray, $inputArray)) > 0
is true when at least one element of $inputArray is present in $mainArray. Of course,
count(array_intersect($mainArray, $inputArray)) == 0
when no element of $inputArray is present in $mainArray.
Use the one that matches your needs.

php count only integer keys of an array

Exist some simple function for count only the integer keys of an array?
for example i have this array:
0 => "string"
1 => "string"
"#aaa" => "string"
I need count only the first two element without using a custom foreach loop.
To count the integer keys, try
count(array_filter(array_keys($array), function($key) {
return is_int($key);
}));
Do a check on each key to loop through only the numbered keys:
foreach( $arr as $key => $value ) {
if( is_numeric($key) ) { //Only numbered keys will pass
//Do whatever you want
}
}
Here's a simple solution:
$int_keys = count(array_filter(array_keys($arr), 'is_int'));

Recursively remove empty elements and subarrays from a multi-dimensional array

I can't seem to find a simple, straight-forward solution to the age-old problem of removing empty elements from arrays in PHP.
My input array may look like this:
Array ( [0] => Array ( [Name] => [EmailAddress] => ) )
(And so on, if there's more data, although there may not be...)
If it looks like the above, I want it to be completely empty after I've processed it.
So print_r($array); would output:
Array ( )
If I run $arrayX = array_filter($arrayX); I still get the same print_r output. Everywhere I've looked suggests this is the simplest way of removing empty array elements in PHP5, however.
I also tried $arrayX = array_filter($arrayX,'empty_array'); but I got the following error:
Warning: array_filter() [function.array-filter]: The second argument, 'empty_array', should be a valid callback
What am I doing wrong?
Try using array_map() to apply the filter to every array in $array:
$array = array_map('array_filter', $array);
$array = array_filter($array);
Demo: http://codepad.org/xfXEeApj
There are numerous examples of how to do this. You can try the docs, for one (see the first comment).
function array_filter_recursive($array, $callback = null) {
foreach ($array as $key => & $value) {
if (is_array($value)) {
$value = array_filter_recursive($value, $callback);
}
else {
if ( ! is_null($callback)) {
if ( ! $callback($value)) {
unset($array[$key]);
}
}
else {
if ( ! (bool) $value) {
unset($array[$key]);
}
}
}
}
unset($value);
return $array;
}
Granted this example doesn't actually use array_filter but you get the point.
The accepted answer does not do exactly what the OP asked. If you want to recursively remove ALL values that evaluate to false including empty arrays then use the following function:
function array_trim($input) {
return is_array($input) ? array_filter($input,
function (& $value) { return $value = array_trim($value); }
) : $input;
}
Or you could change the return condition according to your needs, for example:
{ return !is_array($value) or $value = array_trim($value); }
If you only want to remove empty arrays. Or you can change the condition to only test for "" or false or null, etc...
Following up jeremyharris' suggestion, this is how I needed to change it to make it work:
function array_filter_recursive($array) {
foreach ($array as $key => &$value) {
if (empty($value)) {
unset($array[$key]);
}
else {
if (is_array($value)) {
$value = array_filter_recursive($value);
if (empty($value)) {
unset($array[$key]);
}
}
}
}
return $array;
}
Try with:
$array = array_filter(array_map('array_filter', $array));
Example:
$array[0] = array(
'Name'=>'',
'EmailAddress'=>'',
);
print_r($array);
$array = array_filter(array_map('array_filter', $array));
print_r($array);
Output:
Array
(
[0] => Array
(
[Name] =>
[EmailAddress] =>
)
)
Array
(
)
array_filter() is not type-sensitive by default. This means that any zero-ish, false-y, null, empty values will be removed. My links to follow will demonstrate this point.
The OP's sample input array is 2-dimensional. If the data structure is static then recursion is not necessary. For anyone who would like to filter the zero-length values from a multi-dimensional array, I'll provide a static 2-dim method and a recursive method.
Static 2-dim Array:
This code performs a "zero-safe" filter on the 2nd level elements and then removes empty subarrays: (See this demo to see this method work with different (trickier) array data)
$array=[
['Name'=>'','EmailAddress'=>'']
];
var_export(
array_filter( // remove the 2nd level in the event that all subarray elements are removed
array_map( // access/iterate 2nd level values
function($v){
return array_filter($v,'strlen'); // filter out subarray elements with zero-length values
},$array // the input array
)
)
);
Here is the same code as a one-liner:
var_export(array_filter(array_map(function($v){return array_filter($v,'strlen');},$array)));
Output (as originally specified by the OP):
array (
)
*if you don't want to remove the empty subarrays, simply remove the outer array_filter() call.
Recursive method for multi-dimensional arrays of unknown depth: When the number of levels in an array are unknown, recursion is a logical technique. The following code will process each subarray, removing zero-length values and any empty subarrays as it goes. Here is a demo of this code with a few sample inputs.
$array=[
['Name'=>'','Array'=>['Keep'=>'Keep','Drop'=>['Drop2'=>'']],'EmailAddress'=>'','Pets'=>0,'Children'=>null],
['Name'=>'','EmailAddress'=>'','FavoriteNumber'=>'0']
];
function removeEmptyValuesAndSubarrays($array){
foreach($array as $k=>&$v){
if(is_array($v)){
$v=removeEmptyValuesAndSubarrays($v); // filter subarray and update array
if(!sizeof($v)){ // check array count
unset($array[$k]);
}
}elseif(!strlen($v)){ // this will handle (int) type values correctly
unset($array[$k]);
}
}
return $array;
}
var_export(removeEmptyValuesAndSubarrays($array));
Output:
array (
0 =>
array (
'Array' =>
array (
'Keep' => 'Keep',
),
'Pets' => 0,
),
1 =>
array (
'FavoriteNumber' => '0',
),
)
If anyone discovers an input array that breaks my recursive method, please post it (in its simplest form) as a comment and I'll update my answer.
When this question was asked, the latest version of PHP was 5.3.10. As of today, it is now 8.1.1, and a lot has changed since! Some of the earlier answers will provide unexpected results, due to changes in the core functionality. Therefore, I feel an up-to-date answer is required. The below will iterate through an array, remove any elements that are either an empty string, empty array, or null (so false and 0 will remain), and if this results in any more empty arrays, it will remove them too.
function removeEmptyArrayElements( $value ) {
if( is_array($value) ) {
$value = array_map('removeEmptyArrayElements', $value);
$value = array_filter( $value, function($v) {
// Change the below to determine which values get removed
return !( $v === "" || $v === null || (is_array($v) && empty($v)) );
} );
}
return $value;
}
To use it, you simply call removeEmptyArrayElements( $array );
If used inside class as helper method:
private function arrayFilterRecursive(array $array): array
{
foreach ($array as $key => &$value) {
if (empty($value)) {
unset($array[$key]);
} else if (is_array($value)) {
$value = self::arrayFilterRecursive($value);
}
}
return $array;
}

selecting an array key based on partial string

I have an array and in that array I have an array key that looks like, show_me_160 this array key may change a little, so sometimes the page may load and the array key maybe show_me_120, I want to now is possible to just string match the array key up until the last _ so that I can check what the value is after the last underscore?
one solution i can think of:
foreach($myarray as $key=>$value){
if("show_me_" == substr($key,0,8)){
$number = substr($key,strrpos($key,'_'));
// do whatever you need to with $number...
}
}
I ran into a similar problem recently. This is what I came up with:
$value = $my_array[current(preg_grep('/^show_me_/', array_keys($my_array)))];
you would have to iterate over your array to check each key separately, since you don't have the possibility to query the array directly (I'm assuming the array also holds totally unrelated keys, but you can skip the if part if that's not the case):
foreach($array as $k => $v)
{
if (strpos($k, 'show_me_') !== false)
{
$number = substr($k, strrpos($k, '_'));
}
}
However, this sounds like a very strange way of storing data, and if I were you, I'd check if there's not an other way (more efficient) of passing data around in your application ;)
to search for certain string in array keys you can use array_filter(); see docs
// the array you'll search in
$array = ["search_1"=>"value1","search_2"=>"value2","not_search"=>"value3"];
// filter the array and assign the returned array to variable
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($key){
return(strpos($key,'search_') !== false);
},
// flag to let the array_filter(); know that you deal with array keys
ARRAY_FILTER_USE_KEY
);
// print out the returned array
print_r($foo);
if you search in the array values you can use the flag 0 or leave the flag empty
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($value){
return(strpos($value,'value') !== false);
},
// flag to let the array_filter(); know that you deal with array value
0
);
or
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($value){
return(strpos($value,'value') !== false);
}
);
if you search in the array values and array keys you can use the flag ARRAY_FILTER_USE_BOTH
$foo = array_filter(
// the array you wanna search in
$array,
// callback function to search for certain sting
function ($value, $key){
return(strpos($key,'search_') !== false or strpos($value,'value') !== false);
},
ARRAY_FILTER_USE_BOTH
);
in case you'll search for both you have to pass 2 arguments to the callback function
You can also use a preg_match based solution:
foreach($array as $str) {
if(preg_match('/^show_me_(\d+)$/',$str,$m)) {
echo "Array element ",$str," matched and number = ",$m[1],"\n";
}
}
filter_array($array,function ($var){return(strpos($var,'searched_word')!==FALSE);},);
return array 'searched_key' => 'value assigned to the key'
foreach($myarray as $key=>$value)
if(count(explode('show_me_',$event_key)) > 1){
//if array key contains show_me_
}
More information (example):
if array key contain 'show_me_'
$example = explode('show_me_','show_me_120');
print_r($example)
Array ( [0] => [1] => 120 )
print_r(count($example))
2
print_r($example[1])
120

Categories