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
Related
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 have two arrays I want to compare these two arrays and find the match. If 807 and 200 appears in same keys like 131 then create third array
array(131=>(807,200));
array1:-
Array([0] => 807,[1] => 200)
array2 :-
$mat= Array([0] => Array([131] => 807),[1] => Array([132] => 807),[2] => Array([125] => 200),[3] => Array([131] => 200))
My code:
<?php
$filtered = array();
array_walk_recursive($matchingskusarr, function($val, $key) use(&$filtered) {
if ($key === 131) {
echo "The key $key has the value $val<br>";
$filtered[$val] = $key;
}
});
echo "<pre>";
print_r($filtered);
echo "</pre>";
?>
You can use array_column like this:
$filtered = array_column($mat, 131);
//Output: Array ( [0] => 807 [1] => 200 )
Update 1:
$matchingskusarr = Array( 0 => Array(131 => 807), 1 => Array(132 => 807),2 => Array(125 => 200),3 => Array(131 => 200)) ;
$skus = array(0=>807, 1=>200);
function yourMatch($skus, $matchingskusarr) {
$continue = [];
foreach ($matchingskusarr as $array) {
//Get the first key !!!
foreach ($array as $key => $value);
//Column already tested just continue
if(isset($continue[$key])) {
continue;
}
//New column we need to check if it matches our $skus
$column = array_column($matchingskusarr, $key);
if($column == $skus) {
return [$key => $column ];
}
$continue[$key] = true;
}
return null;
}
print_r(yourMatch($skus, $matchingskusarr));
Demo: https://3v4l.org/Cr2L4
I have an array, looking like this:
[lund] => Array
(
[69] => foo
)
[berlin] => Array
(
[138] => foox2
)
[tokyo] => Array
(
[180] => foox2
[109] => Big entrance
[73] => foo
)
The thing is that there were duplicate keys, so I re-arranged them so I can search more specifically, I thought.
Previously I could just
$key = array_search('foo', $array);
to get the key but now I don't know how.
Question: I need key for value foo, from tokyo. How do I do that?
You can get all keys and value of foo by using this:
foreach ($array as $key => $value) {
$newArr[$key] = array_search('foo', $value);
}
print_r(array_filter($newArr));
Result is:
Array
(
[lund] => 69
[tokyo] => 109
)
If you don't mind about the hard code than you can use this:
array_search('foo', $array['tokyo']);
It just a simple example, you can modify it as per your requirement.
Try this
$a = array(
"land"=> array("69"=>"foo"),
"land1"=> array("138"=>"foo1"),
"land2"=> array('180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'),
);
//print_r($a);
$reply = search_in_array($a, "foo");
print_r($reply);
function search_in_array($a, $search)
{
$result = array();
foreach($a as $key1 => $array ) {
foreach($array as $k => $value) {
if($value == "$search") {
array_push($result,"{$key1}=>{$k}");
breck;
}
}
}
return $result;
}
This function will return the key or null if the search value is not found.
function search($searchKey, $searchValue, $searchArr)
{
foreach ($searchArr as $key => $value) {
if ($key == $searchKey && in_array($searchValue, $value)) {
$results = array_search($searchValue, $value);
}
}
return isset($results) ? $results : null;
}
// var_dump(search('tokyo', 'foo', $array));
Since Question: I need key for value foo, from tokyo. How do i do that?
$key = array_search('foo', $array['tokyo']);
As a function:
function getKey($keyword, $city, $array) {
return array_search($keyword, $array[$city]);
}
// PS. Might be a good idea to wrap this array in an object and make getKey an object method.
If you want to get all cities (for example to loop through them):
$cities = array_keys($array);
I created solution using array iterator. Have a look on below solution:
$array = array(
'lund' => array
(
'69' => 'foo'
),
'berlin' => array
(
'138' => 'foox2'
),
'tokyo' => array
(
'180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'
)
);
$main_key = 'tokyo'; //key of array
$search_value = 'foo'; //value which need to be search
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $key => $value) {
$keys = array();
if ($value == $search_value) {
$keys[] = $key;
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$keys[] = $iterator->getSubIterator($i)->key();
}
$key_paths = array_reverse($keys);
if(in_array($main_key, $key_paths) !== false) {
echo "'{$key}' have '{$value}' value which traverse path is: " . implode(' -> ', $key_paths) . '<br>';
}
}
}
you can change value of $main_key and $serch_value according to your parameter. hope this will help you.
<?php
$lund = [
'69' => 'foo'
];
$berlin = [
'138' => 'foox2'
];
$tokyo = [
'180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'
];
$array = [
$lund,
$berlin,
$tokyo
];
echo $array[2]['180']; // outputs 'foox2' from $tokyo array
?>
If you want to get key by specific key and value then your code should be:
function search_array($array, $key, $value)
{
if(is_array($array[$key])) {
return array_search($value, $array[$key]);
}
}
echo search_array($arr, 'tokyo', 'foo');
try this:
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 'On');
$array=array("lund" => array
(
69 => "foo"
),
"berlin" => array
(
138 => "foox2"
),
"tokyo" => array
(
180 => "foox2",
109 => "Big entrance",
73 => "foo"
));
function search($array, $arrkey1, $arrvalue2){
foreach($array as $arrkey=>$arrvalue){
if($arrkey == $arrkey1){
foreach($arrvalue as $arrkey=>$arrvalue){
if(preg_match("/$arrvalue/i",$arrvalue2))
return $arrkey;
}
}
}
}
$result=search($array, "tokyo", "foo"); //$array=array; tokyo="inside array to check"; foo="value" to check
echo $result;
You need to loop through array, since its 2 dimensional in this case. And then find corresponding value.
foreach($arr as $key1 => $key2 ) {
foreach($key2 as $k => $value) {
if($value == "foo") {
echo "{$k} => {$value}";
}
}
}
This example match key with $value, but you can do match with $k also, which in this case is $key2.
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;
}
?>
Right now i got an array which has some sort of information and i need to create a table from it. e.g.
Student{
[Address]{
[StreetAddress] =>"Some Street"
[StreetName] => "Some Name"
}
[Marks1] => 100
[Marks2] => 50
}
Now I want to create database table like which contain the fields name as :
Student_Address_StreetAddress
Student_Address_StreetName
Student_Marks1
Student_Marks2
It should be recursive so from any depth of array it can create the string in my format.
You can use the RecursiveArrayIterator and the RecursiveIteratorIterator (to iterate over the array recursively) from the Standard PHP Library (SPL) to make this job relatively painless.
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$keys = array();
foreach ($iterator as $key => $value) {
// Build long key name based on parent keys
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$key = $iterator->getSubIterator($i)->key() . '_' . $key;
}
$keys[] = $key;
}
var_export($keys);
The above example outputs something like:
array (
0 => 'Student_Address_StreetAddress',
1 => 'Student_Address_StreetName',
2 => 'Student_Marks1',
3 => 'Student_Marks2',
)
(Working on it, here is the array to save the trouble):
$arr = array
(
'Student' => array
(
'Address' => array
(
'StreetAddress' => 'Some Street',
'StreetName' => 'Some Name',
),
'Marks1' => '100',
'Marks2' => '50',
),
);
Here it is, using a modified version of #polygenelubricants code:
function dfs($array, $parent = null)
{
static $result = array();
if (is_array($array) * count($array) > 0)
{
foreach ($array as $key => $value)
{
dfs($value, $parent . '_' . $key);
}
}
else
{
$result[] = ltrim($parent, '_');
}
return $result;
}
echo '<pre>';
print_r(dfs($arr));
echo '</pre>';
Outputs:
Array
(
[0] => Student_Address_StreetAddress
[1] => Student_Address_StreetName
[2] => Student_Marks1
[3] => Student_Marks2
)
Something like this maybe?
$schema = array(
'Student' => array(
'Address' => array(
'StreetAddresss' => "Some Street",
'StreetName' => "Some Name",
),
'Marks1' => 100,
'Marks2' => 50,
),
);
$result = array();
function walk($value, $key, $memo = "") {
global $result;
if(is_array($value)) {
$memo .= $key . '_';
array_walk($value, 'walk', $memo);
} else {
$result[] = $memo . $key;
}
}
array_walk($schema, 'walk');
var_dump($result);
I know globals are bad, but can't think of anything better now.
Something like this works:
<?php
$arr = array (
'Student' => array (
'Address' => array (
'StreetAddress' => 'Some Street',
'StreetName' => 'Some Name',
),
'Marks1' => array(),
'Marks2' => '50',
),
);
$result = array();
function dfs($data, $prefix = "") {
global $result;
if (is_array($data) && !empty($data)) {
foreach ($data as $key => $value) {
dfs($value, "{$prefix}_{$key}");
}
} else {
$result[substr($prefix, 1)] = $data;
}
}
dfs($arr);
var_dump($result);
?>
This prints:
array(4) {
["Student_Address_StreetAddress"] => string(11) "Some Street"
["Student_Address_StreetName"] => string(9) "Some Name"
["Student_Marks1"] => array(0) {}
["Student_Marks2"] => string(2) "50"
}
function getValues($dataArray,$strKey="")
{
global $arrFinalValues;
if(is_array($dataArray))
{
$currentKey = $strKey;
foreach($dataArray as $key => $val)
{
if(is_array($val) && !empty($val))
{
getValues($val,$currentKey.$key."_");
}
else if(!empty($val))
{
if(!empty($strKey))
$strTmpKey = $strKey.$key;
else
$strTmpKey = $key;
$arrFinalValues[$strTmpKey]=$val;
}
}
}
}