PHP value in an array - php

Hi I'm working on a checking a given array for a certain value.
my array looks like
while($row = mysqli_fetch_array($result)){
$positions[] = array( 'pos' => $row['pos'], 'mark' => $row['mark'] );
}
I'm trying to get the info from it with a method like
<?php
if(in_array('1', $positions)){
echo "x";
}
?>
This I know the value '1' is in the array but the x isn't being sent as out put. any suggestions on how to get "1" to be recognized as being in the array?
Edit:
I realize that this is an array inside of an array. is it possible to combine in_array() to say something like:
"is the value '1' inside one of these arrays"

in_array is not recursive. You're checking if 1 is in an array of arrays which doesn't make sense. You'll have to loop over each element and check that way.
$in = false;
foreach ($positions as $pos) {
if (in_array(1, $pos)) {
$in = true;
break;
}
}

in_array only checks the first level. In this case, it only sees a bunch of arrays, no numbers of any kind. Instead, consider looping through the array with foreach, and check if that 1 is where you expect it to be.

That's because $positions is an array of arrays (a multi-dimensional array).
It contains no simple '1'.
Try a foreach-loop instead:
foreach($postions as $value)
if ($value["pos"] == '1')
echo "x ".$value["mark"];

The problem is that 1 isn't actually in the array. It's in one of the array's within the array. You are comparing the value 1 to the value Array which obviously isn't the same.
Something like this should get you started:
foreach ($positions as $position) {
if ($position['pos'] == 1) {
echo "x";
break;
}
}

Your array $positions is recursive, due to the fact that you use $positions[] in your first snippet. in_array is not recursive (see the PHP manual). Therefore, you need a custom function which works with recursive arrays (source):
<?php
function in_arrayr( $needle, $haystack ) {
foreach( $haystack as $v ){
if( $needle == $v )
return true;
elseif( is_array( $v ) )
if( in_arrayr( $needle, $v ) )
return true;
}
return false;
}
?>
Instead of calling in_array() in your script, you should now call in_arrayr().

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.

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

Search an array for a matching string

I am looking for away to check if a string exists as an array value in an array is that possible and how would I do it with PHP?
If you simply want to know if it exists, use in_array(), e.g.:
$exists = in_array("needle", $haystack);
If you want to know its corresponding key, use array_search(), e.g.:
$key = array_search("needle", $haystack);
// will return key for found value, or FALSE if not found
You can use PHP's in_array function to see if it exists, or array_search to see where it is.
Example:
$a = array('a'=>'dog', 'b'=>'fish');
in_array('dog', $a); //true
in_array('cat', $a); //false
array_search('dog', $a); //'a'
array_search('cat', $a); //false
Php inArray()
Incidentally, although you probably should use either in_array or array_search like these fine gentlemen suggest, just so you know how to do a manual search in case you ever need to do one, you can also do this:
<?php
// $arr is the array to be searched, $needle the string to find.
// $found is true if the string is found, false otherwise.
$found = false;
foreach($arr as $key => $value) {
if($value == $needle) {
$found = true;
break;
}
}
?>
I know it seems silly to do a manual search to find a string - and it is - but you may one day wish to do more complicated things with arrays, so it's good to know how to actually get at each $key-$value pair.
Here you go:
http://www.php.net/manual/en/function.array-search.php
The array_search function does exactly what you want.
$index = array_search("string to search for", $array);
Say we have this array:
<?php
$array = array(
1 => 'foo',
2 => 'bar',
3 => 'baz',
);
?>
If you want to check if the element 'foo' is in the array, you would do this
<?php
if(in_array('foo', $array)) {
// in array...
}else{
// not in array...
}
?>
If you want to get the array index of 'foo', you would do this:
<?php
$key = array_search('foo', $array);
?>
Also, a simple rule for the order of the arguments in these functions is: "needle, then haystack"; what you're looking for should be first, and what you're looking in second.

Categories