No doubt it has been discussed few million times here and yes once again I am posting something related with it.
I have the following code.
$address = "#&#&#&";
$addr = explode("#&",$address);
it returns
Array
(
[0] =>
[1] =>
[2] =>
[3] =>
)
Now the values are empty.So I am doing a check.
If(!empty($addr))
{
echo 'If print then something wrong';
}
And it still prints that line.Not frustrated yet but will be soon
Run array_filter() to remove empty entries, then check if the array itself is empty()
if (empty(array_filter($addr)))
Note that array_filter() without a callback will remove any "falsey" entries, including 0
To check if the array contains no values you could loop the array and unset the no values and then check if the array is empty like the following.
$addresses = "#&#&#&";
$addresses = explode("#&", $addresses);
foreach ( $addresses as $key => $val ) {
if ( empty($val) ) {
unset($addresses[$key]);
}
}
if ( empty($addresses) ) {
echo 'there are no addresses';
}
else {
// do something
}
This is not an empty array, empty array has no elements, your have four elements, each being an empty string, this is why empty is returning false.
You have to iterate over elements and test whether they are all empty, like
$empty=True;
foreach ($addr as $el){
if ($el){
$empty=False;
break;
}
}
if (!$empty) echo "Has values"; else echo "Empty";
You are checking if the array contains elements in it. What you want to do is check if the elements in the array are empty strings.
foreach ($addr as $item) {
if (empty($item)) {
echo 'Empty string.';
} else {
echo 'Value is: '.item;
}
}
The array is not empty, it has 4 items. Here's a possible solution:
$hasValues = false;
foreach($addr as $v){
if($v){
$hasValues = true;
break;
}
}
if(!$hasValues){
echo 'no values';
}
Related
Is there any elegant way to check if
$review['passenger'] has any $review['passenger']['*']?
Try with is_array(). It will check if it is an array or not -
if(is_array($review['passenger'])) {
// is an array
}
Or if you want to check if some key is present or not then -
if(array_key_exists('key', $review['passenger'])) { ... }
I believe Danius was using "['*']" to reference "one or more sub-arrays", instead of specifying it as "the" sub-array.
About his question, the only way to verify if a specific KEY of your array has sub-arrays is checking its sub-items, one by one, to identify if any one of them is an array.
It may not be "elegant", but it is definitively functional:
function has_array($arr) {
$has_array = false;
foreach ($arr as $item):
if (is_array($item)):
$has_array = true;
break;
endif;
endforeach;
return $has_array;
}
Simply call the function this way:
$result = has_array($review['passenger']);
I hope it helps.
You can use array_key_exists:
$array = array(
"passenger" => array(
"*" => "ok"
)
);
if(array_key_exists('*', $array['passenger'])){
echo "ok";
} else {
echo "not ok";
}
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]);
}
}
Let’s say I have two arrays, one is of keys I require, the other is an array I want to test against.
In the array of keys I require, each key might have a value which is itself an array of keys I require, and so on.
Here’s the function so far:
static function keys_exist_in_array(Array $required_keys, Array $values_array, &$error)
{
foreach($required_keys as $key)
{
// Check required key is set in the values array
//
if (! isset($values_array[$key]))
{
// Required key is not set in the values array, set error and return
//
$error = new Error();
return false;
}
// Check the value is an array and perform function on its elements
//
if (is_array($values_array[$key]))
{
Static::keys_exist_in_array($required_keys[$key], $values_array[$key], $error);
}
return true;
}
}
My problem is that the array I want to submit to $required_keys CAN look like this:
$required_keys = array(
‘key1’,
‘key2’,
‘key3’,
‘key4’ = array(
‘key1’,
‘key2’,
‘key3’ = array(
‘key1’
)
)
);
Obviously the problem here is that foreach only finds each key, e.g. ‘key4’, rather than the values without their own value, e.g. ‘key1’, ‘key2’, ‘key3’.
But if I loop through with a standard for loop, I only get the values, key1, key2, key3.
What’s a better way of doing this?
Thanks
Several problems:
$key is the element of the array, not a key, so you
You shouldn't return false as soon as you see a non-matching element, because there could be a matching element later in the array. Instead, you should return true as soon as you find a match. Once you find a match, you don't need to keep searching.
You need to do the isarray() test first, because you'll get an error if $key is an array and you try to use $values_array[$key]. And it should be isarray($key), not isarray($values_array[$key]).
You need to test the value of the recursive call. If it succeeded, you can return immediately.
You should only return false after you finish the loop and don't find anything.
static function keys_exist_in_array(Array $required_keys, Array $values_array, &$error)
{
foreach($required_keys as $key)
{
// Check the value is an array and perform function on its elements
//
if (is_array($key))
{
$result = Static::keys_exist_in_array($required_keys[$key], $values_array[$key], $error);
if ($result) {
return true;
}
}
// Check required key is set in the values array
//
elseif (isset($values_array[$key]))
{
return true;
}
}
$error = new Error();
return false;
}
Convert the array to a key => value array with an empty value for the "keys" that don't have a value.
$arr = [
'a',
'b' => ['foo' => 1, 'bar' => 'X'],
'c' => ['baz' => 'Z'],
'd'
];
$res = [];
$keys = array_keys($arr);
$vals = array_values($arr);
foreach ($vals as $i => $v) {
if (is_array($v)) {
$res[$keys[$i]] = $v;
} else {
$res[$v] = [];
}
}
print_r($res);
Result:
Array
(
[a] => Array
(
)
[b] => Array
(
[foo] => 1
[bar] => X
)
[c] => Array
(
[baz] => Z
)
[d] => Array
(
)
)
Returning false here is the correct action if you require that ALL the $required_keys exist, because you want it to stop looking as soon as it finds a missing key.
static function keys_exist_in_array(Array $required_keys, Array $values_array, &$error)
{
foreach($required_keys as $key=>$value)
{
//check if this value is an array
if (is_array($value))
{
if (!array_key_exists($key, $values_array)
|| !Static::keys_exist_in_array($value, $values_array[$key], $error);){
$error = new Error();
return false;
}
}
// Since this value is not an array, it actually represents a
// key we need in the values array, so check if it is set
// in the values array
elseif (!array_key_exists($value, $values_array))
{
// Required key is not set in the values array, set error and return
$error = new Error();
return false;
}
}
//All elements have been found, return true
return true;
}
lets say i have a array
array
array
key1 = 'hello im a text'
key2 = true;
key3 = '><><';
array
array
key1 = 'hello another text'
key2 = 'im a text too'
key3 = false;
array
key1 = ')(&#'
array
key1 = 'and so on'
how can i get something like below from the above arrays?
array
1 => 'hello im a text';
2 => 'hello another text;
3 => 'im a text too';
4 => 'and so on';
heres what ive done
$found = array();
function search_text($item, $key)
{
global $found;
if (strlen($item) > 5)
{
$found[] = $item;
}
}
array_walk_recursive($array, 'search_text');
var_dump($found);
but somehow it doesn't work
Try something similar to this:
function array_simplify($array, $newarray=array()) { //default of $newarray to be empty, so now it is not a required parameter
foreach ($array as $i) {
if (is_array($i)) { //if it is an array, we need to handle differently
$newarray = array_simplify($i, $newarray); // recursively calls the same function, since the function only appends to $newarray, doesn't reset it
continue; // goes to the next value in the loop, we know it isn't a string
}
if (is_string($i) && strlen($i)>5) { // so we want it in the one dimensional array
$newarray[] = $i; //append the value to $newarray
}
}
return $newarray; // passes the new array back - thus also updating $newarray after the recursive call
}
My note: I haven't tested this, if there's bugs, please tell me and I'll try to fix them.
Something like this should work,
as condition i've used
if(is_string($son))
in order to get some results, you can adjust it as you prefer
$input = <your input array>;
$output = array();
foreach($input AS $object)
{
search_text($object,$output);
}
var_dump($output);
function search_text($object, &$output)
{
foreach($object AS $son)
{
if(is_object($son))
{
search_text($son, $output);
}
else
{
if(is_string($son))
{
$output[] = $son;
}
}
}
}
Description:
search_text gets 2 parameters: the $object and the resulting array $output.
It checks foreach object's property if it is an object or not.
If it is then that object needs to be checked itself,
otherwise search_text checks if the input is a string, if it is the it is stored into the $output array
I have searched and found nothing on this.
I would like some advice or pointers on how I could search a multi dimensional array and update if a value exists or insert if it doesn't exist.
Eg. at the moment I create an array with these values like this:
Array
(
[0] => Array
(
[quantity] => 1
[supplier_paypal] => paypalaccount1#paypal.com
[supplier_price] => 10
)
[1] => Array
(
[quantity] => 2
[supplier_paypal] => paypalaccount2#paypal.com
[supplier_price] => 20
)
)
Now this is great but it just loops though and can create duplicate email addresses in the array. I need something that I can put in the loop that searches to see if the email exists and if it does then just merely adds the supplier prices together.
Any help or ideas?
Heres what I have tried:
$arrIt = new RecursiveIteratorIterator(
new RecursiveArrayIterator($this->data['payrecipient_data']));
foreach ($arrIt as $sub) {
$subArray = $arrIt->getSubIterator();
if ($subArray['supplier_paypal'] === $supplier_info['supplier_paypal']) {
$this->data['payrecipient_dup'][] = iterator_to_array($subArray);
} else {
$this->data['payrecipient_nondup'][] = iterator_to_array($subArray);
}
}
This just enabled me to search through and seperate the arrays into groups of duplicated and none duplicated.
But I don't know where to start with updating an array so I got lost and stuck.
$needle = 'foo#bar.com';
$found = false;
foreach ($array as &$element) {
if ($element['supplier_paypal'] == $needle) {
// update some data
$element['foo'] = 'bar';
$found = true;
break;
}
}
unset($element);
if (!$found) {
$array[] = array('supplier_paypal' => $needle, ...);
}
There are more elegant ways to index the data to find it quicker without looping through the whole thing every time, but this is essentially the basic algorithm you're looking for.
Taken from one of the comments in PHP's str_replace() documentation:
<?php
function str_replace_json($search, $replace, $subject){
return json_decode(str_replace($search, $replace, json_encode($subject)));
}
?>
Suppose your array name is arr1.
Use the following
$email = /*Your email to check*/;
$flag = 0; // td check if email has found or not
foreach($arr1 as $temp)
{
if($temp->supplier_paypal == $email) //email matches
{
/*add supplier price....*/
$flag=1;
}
}
if($flag == 0)
{
/*Your logic */
}