I have the following query:
//product density
$stmt_density = $conn->prepare("SELECT density FROM product_density
WHERE product_id = :productid ");
$stmt_density->execute(array(':productid' => "$pid"));
$density = $stmt_density->fetchAll();
If density is not present the value will be "NULL".
var_dump($density);
gives following output:
array(1) { [0]=> array(2) { ["density"]=> NULL [0]=> NULL } }
I need to check whether the array is having values or not and to provide select options, if array not empty.
Depending on whether you expect to get back multiple results from your query could change the answer, especially if you get back say 1 result with a NULL and one without. But you could do...
function validResult($density) {
foreach($density as $item) {
if($item["density"] == NULL) return false;
}
return true;
}
if(validResult($density))
echo "We have values";
else
echo "Array contains null";
The function will return false if any result has null, regardless of how many are not null
Try something like this
function check($array, $key)
{
if(array_key_exists($key, $array)) {
if (is_null($array[$key])) {
echo $key . ' is null';
} else {
echo $key . ' is set';
}
}
}
I think you are trying to check for null values in an array try
function array_key_exists_r($needle, $haystack)
{
foreach ($haystack as $v) {
foreach ($v as $k=>$v1) {
if(empty($v1) || $v1 ==$needle)
$result[$k] = $v1;
}
if ($result) return $result;
}
}
$r = array_key_exists_r('NULL', $density);
print_r($r); //Array ( [density] => [0] => )
Function will give you all empty or NULL keys as an array
Related
I have this kind of list of variables:
$item[1]['Value']
$item[2]['Value']
...
$item[50]['Value']
Some of them are null.
How do I check if at least one of them is not empty, and in this case, define that one (whether first case or last case) as a new variable?
P.S. What is the name of an $var[number]['foo'] format? Is it an array?
A simple test in using empty() function
if(!empty($item[$i]['value'])
{
echo "exists";
}else{
echo "is not set";
}
If you want affect a new value if it not exists or not defined, you can use null coalescing operator
$item[$i]['value'] = $item[$i]['value'] ?? $newvalue;
to check atleast one of them is not empty
<?php
$atleast=0;//all are empty
for($i=0;$i<count($item);$i++)
{
if(!empty($item[$i]['value']))
$atleast=1;//one is empty;
}
if($atleast==1)
echo "there is more than one element which are not empty";
else
echo "all are emtpy";
?>
This sets the last found used element as newVariable.
for($i = 0; $i < sizeOf($item); i ++)
{
if(isset($item[$i]['Value']))
{
$newVariable = $item[$i]['Variable'];
}
}
If you want to use the inner key as a variable name, then you can check whether you can create it and create it if so:
function any($array) {
foreach ($array as $key => $item) {
if ($item) return $key;
}
return false;
}
$variableName = any($var);
if ($variableName !== false) {
{$variableName} = "yourvalue";
} else {
//We ran out of variable names
}
P.S. The format of $var[number]['foo'] is an array with number keys on the outside and an array with string keys in the inside.
You could array_filter() and use empty() like this :
// example data
$items = [
['Value' => null],
['Value' => 2],
['Value' => null],
];
// remove elements with 'Value' = null
$filtered = array_filter($items, function($a) { return !is_null($a['Value']); }) ;
$element = null;
// If there is some values inside $filtered,
if (!empty($filtered)) {
// get the first element
$element = reset($filtered) ;
// get its value
$element = $element['Value'];
}
if ($element)
echo $element ;
will outputs:
2
array_filter() return an array with non-empty values (using use function).
empty() checks if an array is empty or not.
reset() gets the first element in an array.
If you want to check all the values of all items of the array you can use foreach.
Example:
$item[1]['Value'] = "A";
$item[2]['Value'] = "B";
$item[4]['Value'] = "";
$item[3]['Value'] = NULL;
foreach ($item as $key => $value) {
if (!empty($value['Value'])) {
echo "$key It's not empty \n";
} else {
echo "$key It's empty \n";
}
}
Result:
1 It's not empty
2 It's not empty
3 It's empty
4 It's empty
Also you can see that the empty function consider NULL as empty.
----- EDIT -----
I forget to add the method to detect if at least one item it's empty, you can use:
Example
$item[1]['Value'] = "A";
$item[2]['Value'] = "B";
$item[4]['Value'] = "";
$item[3]['Value'] = NULL;
foreach ($item as $key => $value) {
if (!empty($value['Value'])) {
$item_result = false;
} else {
$item_result = true;
}
}
if ($item_result) {
echo "At least one item is empty";
} else {
echo "All items have data";
}
Result:
At least one item is empty
<?php
$data =
[
1 => ['foo' => ''],
2 => ['bar' => 'big'],
10 => ['foo' => 'fat']
];
$some_foo = function ($data) {
foreach($data as $k => $v)
if(!empty($v['foo'])) return true;
return false;
};
var_dump($some_foo($data));
$data[10]['foo'] = null;
var_dump($some_foo($data));
Output:
bool(true)
bool(false)
Alternatively you can filter foo values that evaluate to false:
$some_foo = (bool) array_filter(array_column($data, 'foo'));
I have an array called tagcat , like so
$tagcat = array();
....
while ( $stmt->fetch() ) {
$tagcat[$tagid] = array('tagname'=>$tagname, 'taghref'=>$taghref);
}
Using print_r($tagcat) i get the following result set
Array ( [] => Array ( [tagname] => [taghref] => ) )
Using var_dump($tagcat), i get
array(1) { [""]=> array(2) { ["tagname"]=> NULL ["taghref"]=> NULL } }
In php, i want to check if the array is empty. But when using the following conditions, it always finds something in the array, which is not true!
if ( isset($tagcat) ) {
echo 'array is NOT empty';
} else {
echo 'EMPTY!!!';
}
if ( !empty($tagcat) ) {
echo 'array is NOT empty';
} else {
echo 'EMPTY!!!';
}
How do i check if the array is empty?
Use array_filter
if(!array_filter($array)) {
echo "Array is empty";
}
This was to check for the single array. For multi-dimensional array in your case. I think this should work:
$empty = 0;
foreach ($array as $val) {
if(!array_filter($val)) {
$empty = 1;
}
}
if ($empty) {
echo "Array is Empty";
}
If no callback is supplied, all entries of $array equal to FALSE will be removed.
With this it only returns the value which are not empty. See more in the docs example Example #2 array_filter() without callback
If you need to check if there are ANY elements in the array
if (!empty($tagcat) ) { //its $tagcat, not tagcat
echo 'array is NOT empty';
} else {
echo 'EMPTY!!!';
}
Also, if you need to empty the values before checking
foreach ($tagcat as $cat => $value) {
if (empty($value)) {
unset($tagcat[$cat]);
}
}
if (empty($tagcat)) {
//empty array
}
Hope it helps
EDIT: I see that you have edited your $tagcat var. So, validate with vardump($tagcat) your result.
if (empty($array)) {
// array is empty.
}
if you want remove empty elements try this:
foreach ($array as $key => $value) {
if (empty($value)) {
unset($array[$key]);
}
}
For array with single values like
array(2) {
["blue"]=>
int(0)
["red"]=>
int(1)
}
I use this code
<?php
if (array_key_exists('blue',$array))
{
echo "jo";
}
?>
But what code do I need to use for arrays like this
array(2) {
["yellow blue"]=>
int(0)
["red white"]=>
int(1)
}
to check if blue exists?
My take:
if(preg_grep('/blue/', array_keys($array))) { echo 'found'; }
Or if you want to get them:
$matches = preg_grep('/blue/', array_keys($array));
print_r($matches);
$partialKey = 'blue';
$byPartialKey = function ($key) use ($partialKey) {
$parts = explode(' ', $key);
return in_array($partialKey, $parts);
};
$result = array_filter (array_keys($input), $byPartialKey);
$result now contains all keys, that somehow contains $partialKey.
you can do using regular expression
search='blue';
foreach ($array as $key => $value) {
if (preg_match('~'.$search.'~i',$key)) {
echo "jo";
}
}
The \b in the pattern indicates a word boundary, so only the distinct
word "blue" is matched, and not a word partial like "bluegreen"
search='blue';
foreach ($array as $key => $value) {
if (preg_match('/\b'.$search.'\b/i',$key)) {
echo "jo";
}
}
Reference
I would do it like this:
function subkey_exists($string, $array) {
foreach($array as $key => $value) {
$sub_keys = explode(" ", $key);
if(in_array($string,$sub_keys)) {
return true;
}
}
return false;
}
[edit]
updated to your requirements
Yet another array_filter solution :
<?php
function find_keys_like($key, $array) {
return array_filter(array_keys($array), function($k) use (&$key) {
return strpos($k, $key) > -1;
});
}
function array_has_key_like($key, $array) {
return count(find_keys_like($key, $array)) > 0;
}
//test
$a = array('blue' => 1, 'yellow blue' => 2, 'green' => 3);
print_r(find_keys_like('blue', $a));
echo 'blue exists ? ' . (array_has_key_like('blue', $a) ? 'yes' : 'no') . PHP_EOL;
/** result :
Array
(
[0] => blue
[1] => yellow blue
)
blue exists ? yes
*/
Hi all I have an array
$data = array("https://lh6.googleusercontent.com/-pXObolgHAdo/UbBLHGz1R6I/AAAAAAAAAbg/aAkGHbXQ6WU/w958-h715-no/111.jpg",
"https://lh4.googleusercontent.com/-F_ngXcmSdxY/UbBLypozWvI/AAAAAAAAAew/juDGaqNUiSc/w958-h715-no/411.jpg",
"https://lh6.googleusercontent.com/-dxOkxkoZd0k/Ua3jQFu2WqI/AAAAAAAAAQc/eYX-u6mtF3k/w958-h715-no/113.jpg",
"https://lh5.googleusercontent.com/-8XTn3y4s8IY/Ua3jTOTRmxI/AAAAAAAAAQw/6qQA7xtagEo/w958-h715-no/121.jpg");
How can I get specific data from the array using a clause?
eg. I want to pull a data from the array with 121.jpg.
Thanks!
You can loop the array and check the value:
while (list($key, $value) = each ($data)) {
if(strpos($value, '121.jpg') !== false)
{
var_dump($value);
}
}
May be you mean Closure ? What if there are multiple images with the same name ?
function get_image_url($name, array $images) {
$image_url = array_filter($images, function($value) use ($name) {
return (preg_replace('/^(.*\/)/', '', $value) == $name);
});
if (0 == sizeof($image_url)) {
return false;
} elseif (1 == sizeof($image_url)) {
return reset($image_url);
}
return $image_url;
}
Example:
$images = array(
"https://lh6.googleusercontent.com/-pXObolgHAdo/UbBLHGz1R6I/AAAAAAAAAbg/aAkGHbXQ6WU/w958-h715-no/111.jpg",
"https://lh4.googleusercontent.com/-F_ngXcmSdxY/UbBLypozWvI/AAAAAAAAAew/juDGaqNUiSc/w958-h715-no/411.jpg",
"https://lh6.googleusercontent.com/-dxOkxkoZd0k/Ua3jQFu2WqI/AAAAAAAAAQc/eYX-u6mtF3k/w958-h715-no/113.jpg",
"https://lh5.googleusercontent.com/-8XTn3y4s8IY/Ua3jTOTRmxI/AAAAAAAAAQw/6qQA7xtagEo/w958-h715-no/121.jpg",
"121.jpg"
);
var_dump(get_image_url('111.jpg', $images));
// string(103) "https://lh6.googleusercontent.com/-pXObolgHAdo/UbBLHGz1R6I/AAAAAAAAAbg/aAkGHbXQ6WU/w958-h715-no/111.jpg"
var_dump(get_image_url('121.jpg', $images));
// array(2) {
// [3] =>
// string(103) "https://lh5.googleusercontent.com/-8XTn3y4s8IY/Ua3jTOTRmxI/AAAAAAAAAQw/6qQA7xtagEo/w958-h715-no/121.jpg"
// [4] =>
// string(7) "121.jpg"
// }
var_dump(get_image_url('invalid.jpg', $images));
// bool(false)
I know this question has been asked before but I haven't been able to get the provided solutions to work.
I'm trying to check if the words in an array match any of the words (or part of the words) in a provided string.
I currently have the following code, but it only works for the very first word in the array. The rest of them always return false.
"input" would be the "haystack" and "value" would be the "needle"
function check($array) {
global $input;
foreach ($array as $value) {
if (strpos($input, $value) !== false) {
// value is found
return true;
} else {
return false;
}
}
}
Example:
$input = "There are three";
if (check(array("one","two","three")) !== false) {
echo 'This is true!';
}
In the above, a string of "There is one" returns as true, but strings of "There are two" or "There are three" both return false.
If a solution that doesn't involve having to use regular expressions could be used, that would be great. Thanks!
The problem here is that check always returns after the first item in $array. If a match is found, it returns false, if not, it returns true. After that return statement, the function is done with and the rest of the items will not be checked.
function check($array) {
global $input;
foreach($array as $value) {
if(strpos($input, $value) !== false) {
return true;
}
}
return false;
}
The function above only returns true when a match is found, or false when it has gone through all the values in $array.
strpos(); is totally wrong here, you should simply try
if ($input == $value) {
// ...
}
and via
if ($input === $value) { // there are THREE of them: =
// ...
}
you can even check if the TYPE of the variable is the same (string, integer, ...)
a more professional solution would be
in_array();
which checks for the existance of the key or the value.
The problem here is that you're breaking out of the function w the return statement..so u always cut out after the first comparison.
you should use in_array() to compare the array values.
function check($array) {
global $input;
foreach ($array as $value) {
if (in_array($value,$input))
{
echo "Match found";
return true;
}
else
{
echo "Match not found";
return false;
}
}
}
You're returning on each iteration of $array, so it will only run once. You could use stristr or strstr to check if $value exists in $input.
Something like this:
function check($array) {
global $input;
foreach ($array as $value) {
if (stristr($input, $value)) {
return true;
}
}
return false;
}
This will then loop through each element of the array and return true if a match is found, if not, after finishing looping it will return false.
If you need to check if each individual item exists in $input you'd have to do something a little bit different, something like:
function check($array) {
global $input;
$returnArr = array();
foreach ($array as $value) {
$returnArr[$value] = (stristr($input, $value)) ? true : false;
}
return $returnArr;
}
echo '<pre>'; var_dump(check($array, $input)); echo '</pre>';
// outputs
array(3) {
["one"]=>
bool(false)
["two"]=>
bool(false)
["three"]=>
bool(true)
}
The reason your code doesnt work, is because you are looping through the array, but you are not saving the results you are getting, so only the last result "counts".
In the following code I passed the results to a variable called $output:
function check($array) {
global $input;
$output = false;
foreach ($array as $value) {
if (strpos($input, $value) != false) {
// value is found
$output = true;
}
}
return $output;
}
and you can use it like so:
$input = "There are two";
$arr = array("one","two","three");
if(check($arr)) echo 'this is true!';