Here is my array ouput
Array
(
[1] => 1
[2] => 2
[3] =>
)
How do I know the [3] => is empty?
foreach ($array as $key => $value) {
if (empty($value))
echo "$key empty <br/>";
else
echo "$key not empty <br/>";
}
My out put showing all is not empty. What is correct way to check is empty?
An other solution:
$array = array('one', 'two', '');
if(count(array_filter($array)) == count($array)) {
echo 'OK';
} else {
echo 'ERROR';
}
http://codepad.org/zF9KkqKl
It works as expected, third one is empty
http://codepad.org/yBIVBHj0
Maybe try to trim its value, just in case that third value would be just a space.
foreach ($array as $key => $value) {
$value = trim($value);
if (empty($value))
echo "$key empty <br/>";
else
echo "$key not empty <br/>";
}
You can check for an empty array by using the following:
if ( !empty(array_filter($array))) {
echo 'OK';
} else {
echo 'EMPTY ARRAY';
}
You can use array_diff() and array_diff_key():
$array = array('one', 'two', '');
$emptyKeys = array_diff_key(array_diff($array,array()),$array);
array_diff() extracts all items which are not the same (therefore leaving out the blanks), array_diff_key gives back the differences to the original array.
$array = array('A', 'B', '');
or
$array = array('A', 'B', ' ');
An other solution:
this work for me
if(in_array(null, $myArray) || in_array('', array_map('trim',$myArray))) {
echo 'Found a empty value in your array!';
}
Here is a simple solution to check an array for empty key values and return the key.
$a = array('string', '', 5);
echo array_search(null, $a);
// Echos 1
To check if array contains an empty key value. Try this.
$b = array('string','string','string','string','','string');
if (in_array(null, $b)) {
echo 'We found a empty key value in your array!';
}
im using in my project like this for check this array
im posting form data like this array('username' => 'john','surname' => 'sins');
public function checkArrayKeyExist($arr) {
foreach ($arr as $key => $value) {
if (!strlen($arr[$key])) {
return false;
}
}
return true;
}
Try this:
<?php
$data=array(
'title' => 'Test Name Four',
'first_name' => '',
'last_name' => 'M',
'field_company' => 'ABC',
'email' => '',
'client_phone_number' => '',
'address_line_1' => '',
'address_line_2' => 'Address 3',
'address_line_3' => '',
'address_line_4' => '',
'post_code' => '',
);
echo '<pre>';
print_r($data);
foreach ($data as $key => $case ) {
echo "$key => ".is_multiArrayEmpty($case)."<br>";
}
function is_multiArrayEmpty($multiarray) {
if(is_array($multiarray) and !empty($multiarray)){
$tmp = array_shift($multiarray);
if(!is_multiArrayEmpty($multiarray) or !is_multiArrayEmpty($tmp)){
return false;
}
return true;
}
if(empty($multiarray)){
return true;
}
return false;
}
?>
Related
I have an array like :
$a =['main'=>
[
'a' => ['1st'],
'b' => ['2nd'],
'c' => ['3th']
];
and I want do like:
if(in_array('1st', $a['main'][x])){
...
}
I need x(now it is a) value too
$resulting_keys = [];
foreach($a['main'] as $key => $value) {
if(in_array('1st', $value)) {
$resulting_keys[] = $key;
}
}
here are working example:
$a = array(
'main'=> array(
'a' => '1st',
'b' => '2nd',
'c' => '3th'
)
);
if(in_array('1st', $a['main'])){
echo 'Yes';
}else{
echo 'No';
}
Maybe try this:
array_filter($a['main'], function($el) {
return in_array('1st', $el);
})
Array filter function is a good solution to filter arrays
http://php.net/manual/en/function.array-filter.php
I have an associative array:
$pair = array(
'S'=>'0',
'I'=>'50',
'P'=>'30'
);
From this pair of key and values, I need first occurrence non zero value from key value pair only,
from my example I'm expecting key I and value 50.
Do something like this:
function findNonZero($var){
// returns whether the input is non zero
return($var > 0);
}
$pair = array(
'S'=>'0',
'I'=>'50',
'P'=>'30'
);
$newPair = array_filter($pair, "findNonZero");
var_dump($newPair); //Contains array of non-zero values
You can do that with usual foreach loop
$pair = array(
'S'=>'0',
'I'=>'50',
'P'=>'30'
);
foreach($pair as $k=>$v) {
if ($v) break;
}
echo "$k => $v"; // I => 50
demo
You can use php functions array_filter(), array_slice(), or use a foreach loop.
<?php
// filter out empty values, and get first item
$value = array_slice(array_filter($pair), 0, 1);
// check not empty
if (!empty($value)) {
// get key
echo 'key => '.array_keys($value)[0].PHP_EOL;
// get value
echo 'value => '.array_values($value)[0];
}
https://3v4l.org/tr3bp
Result:
key => I
value => 50
Or use a loop:
<?php
$value = [];
foreach ($pair as $k => $v) {
if (!empty($v)) {
$value[$k] = $v;
break;
}
}
if (!empty($value)) {
echo 'key => '.array_keys($value)[0].PHP_EOL;
echo 'value => '.array_values($value)[0];
}
https://3v4l.org/tPeAq
Result:
key => I
value => 50
Or use a generator,
<?php
$getNoneEmpty = function() use ($pair) {
foreach ($pair as $key => $value) {
if (!empty($value)) {
yield [$key => $value];
}
}
};
// get first
$value = $getNoneEmpty()->current();
if (!empty($value)) {
echo 'key => '.array_keys($value)[0].PHP_EOL;
echo 'value => '.array_values($value)[0].PHP_EOL;
}
// or loop over all
foreach ($getNoneEmpty() as $value) {
echo 'key => '.array_keys($value)[0].PHP_EOL;
echo 'value => '.array_values($value)[0].PHP_EOL;
}
https://3v4l.org/mnnHl
Result:
key => I
value => 50
key => I
value => 50
key => P
value => 30
Many ways to skin a cat, though, if you don't want the key/value you can also do it differently.
Here is the non-functional code. It does not return anything. Not quite sure what is wrong with the syntax I am using.
function findNeedle($array, $needle) {
return array_values(array_filter($array, function($arrayValue) use($needle) { return $arrayValue['lp_url'] == $needle; } ));
}
$myarray =
0 =>
array (
'lp_url' => 'http://example.com/nx/?utm_source=aa&utm_medium=referral',
'lp_term_id' => 1435949468,
'aff_term_id' => 1445295565,
'offer_term_id' => 1445295996,
),
1 =>
array (
'lp_url' => 'http://example.org/nx/?utm_source=aa&utm_medium=referral',
'lp_term_id' => 1435949468,
'aff_term_id' => 1445295559,
'offer_term_id' => 1445295989,
),
);
$needle = 'http://example.com/nx/?utm_source=aa&utm_medium=referral';
if (is_array($myarray)) {
foreach ($myarray as $value) {
if (is_array($value))
{
$x = findNeedle($value, $needle);
}
}
Extract an array of the data for the lp_url column and check for $needle:
if(in_array($needle, array_column($myarray, 'lp_url'))) {
echo "Found";
} else {
echo "Not found";
}
I am trying to figue out how to check for empty values of an array with certain exceptions. Here is the array:
[name_first] => Name
[name_last] =>
[email] => blah#blah.com
[address] =>
[country] => USA
There are two empty values - name_last & address. Here is the code:
if (in_array(null, $data)) {
echo 'empty values';
}else{
echo 'ok';
}
It will return false as [address] and [name_last] values are empty. How can I ignore a particular key (let's say - [address])? Basically it is supposed to LOOK like this:
if (in_array(null, $data) **&& key_is_not('address', 'hatever')**) {
echo 'empty values';
}else{
echo 'ok';
}
try this :
$data = array('name_first' => "Name",
'name_last' => "",
'email' => "blah#blah.com",
'address' => "",
'country' => "USA");
foreach ($data as $key => $value) {
if($value=="")
echo "$key is Empty\n";
}
Update
To exclude particular keys from the check, you can do this way :
$data = array('name_first' => "",
'name_last' => "",
'email' => "blah#blah.com",
'address' => "",
'country' => "");
$array = array("name_first","country");
foreach ($data as $key => $value) {
if($value=="" and (!in_array($key, $array)))
echo "$key is Empty\n";
}
$input_array = [
'name_first' => 'Name',
'name_last' => '',
'email' => 'blah#blah.com',
'address' => '',
'country' => 'USA',
];
Filter array ignoring the specific keys, here address and name_last
$ignore_search = in_array('', array_filter($input_array, function($k){
return !in_array($k, ['address', 'name_last']);
}, ARRAY_FILTER_USE_KEY));
Here array_filter will unset the keys specified inside.
Will return boolean depending on match found or not, if you want keys, just change in_array with array_search.
This will check to see if the value is set and the length is greater than 0, not an empty string.
foreach($elements as $key => $data)
{
if(!in_array($key, ['address', 'something']))
{
if(count($data) > 0)
{
//stuff
}
}
}
You can also ignore the key by writing a custom function that will handle the keys exception, this way you are more in control if in any case you want to tweak later:
if (in_array_except(null, $data, array("address"))) {
echo 'empty values';
}else{
echo 'ok';
}
The function will be:
function in_array_except($needle, $haystack, $exception = array(), $strict = false) {
if ($strict) {
foreach($haystack as $needle_field => $item) {
if (!in_array($needle_field, $exception) && $item === $needle)
return true;
}
} else {
foreach($haystack as $needle_field => $item) {
if (!in_array($needle_field, $exception) && $item == $needle)
return true;
}
}
return false;
}
With your current data set:
[name_first] => Name
[name_last] =>
[email] => blah#blah.com
[address] =>
[country] => USA
The output with the sample snippet is:
empty values
Try with array_search() like below::
if (array_search("", $arr)) {
echo 'empty values';
} else {
echo 'ok';
}
** Update **
$array_var = array("11" => 111, "22" => 222, "33" => 333, "44" => 444, "55" => "", "66" => 666);
$new_array_var = array();
foreach ($array_var as $key => $value) {
// echo $key . "==>" . $value . "<br/>";
if (isset($value) && $value != "") {
$new_array_var[$key] = $value;
}
}
echo "<pre>";
echo "OLD : <br/>";
print_r($array_var);
echo "<br/><br/>";
echo "NEW : <br/>";
print_r($new_array_var);
echo "</pre>";
$ignore_array = array("address");
$blank_value_keys = array_keys($data,"");
if(sizeof($blank_value_keys)>0 && sizeof(array_diff($ignore_array,$blank_value_keys)>0){
echo "Empty";
}else{
echo "NOT Empty";
}
Add all the keys to be ignored in ignore array list.
array_keys will return all the keys which have blank values.
Next we are checking if size of array returned by array_keys is greater than 0 and there are more keys in $blank_value_keys than $ignore_array than if loop executes.
Note: array_diff will return all the values available in second array but not in first
I'm trying to write a function that takes a multi-dimensional array as input and outputs a multi-line string of keys like the following
['key']['subkey']
['key']['another_subkey']
['key']['another_subkey']['subkey_under_subkey']
['key']['yet_another_subkey']
['another_key']['etc']
Here is my attempt. It has problems when you get to the second level.
function get_array_keys_as_string($array){
$output = "";
foreach($array as $k => $v){
if(is_array($v)){
$string = get_array_keys_as_string($v);
$prepend = "['$k']";
$string = $prepend.str_replace("\n","\n".$prepend, $string);
$output .= $string;
}
else{
$output .= "['$k']\n";
}
}
return $output;
}
I know I need a recursive function, but so far my attempts have come up short.
To get the exact output you asked for use the following:
$arr = array(
"key" => array(
"subkey" => 1,
"another_subkey" => array(
"subkey_under_subkey" => 1
),
"yet_another_subkey" => 1
),
"another_key" => array(
"etc" => 1
)
);
function print_keys_recursive($array, $path = false) {
foreach($array as $key=>$value) {
if(!is_array($value)) {
echo $path."[".$key."]<br/>";
} else {
if($path) {
echo $path."[".$key."]<br/>";
}
print_keys_recursive($value, $path."[".$key."]");
}
}
return;
}
print_keys_recursive($arr);
Output:
[key][subkey]
[key][another_subkey]
[key][another_subkey][subkey_under_subkey]
[key][yet_another_subkey]
[another_key][etc]
Not sure how you want the output since you have not provided an example array, just the result, but here is an example based on the following array,
$array = array(
"key" => array(
"subkey" => 1,
"another_subkey" => array("2", "subkey_under_subkey" => 3),
"yet_another_subkey" => 4
),
"another_key" => array("etc"),
"last_key" => 0
);
Using the following function,
function recursive_keys($arr, $history = NULL)
{
foreach ($arr as $key => $value)
{
if (is_array($value))
recursive_keys($value, $history."['".$key."']");
else
echo $history."['".$key."']\n";
}
}
Output of recursive_keys($array) is,
['key']['subkey']
['key']['another_subkey']['0']
['key']['another_subkey']['subkey_under_subkey']
['key']['yet_another_subkey']
['another_key']['0']
['last_key']
Try this
function arrayMultiKeys($array,$depth = 0){
foreach($array as $k=>$v){
echo "['".$k."']";
if(is_array($v)){
arrayMultiKeys($v,$depth + 1);
}
if($depth == 0 ){
echo "<br>";
}
}
}