Foreach not empty php

Checking if all the array items are empty PHP

I’m adding an array of items from a form and if all of them are empty, I want to perform some validation and add to an error string. So I have:

$array = array( 'RequestID' => $_POST["RequestID"], 'ClientName' => $_POST["ClientName"], 'Username' => $_POST["Username"], 'RequestAssignee' => $_POST["RequestAssignee"], 'Status' => $_POST["Status"], 'Priority' => $_POST["Priority"] ); 

7 Answers 7

You can just use the built in array_filter

If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.

So can do this in one simple line.

array_filter() was already mentioned by @dogmatic69. About performance — I believe simple foreach should be faster than both array_filter() and implode() .

@xzyfer, if(implode($array)) echo ‘..’ would print ‘..’ even if one array element would be (string)»0″ . About foreach being slower than array_filter() — are you sure? How is removing array elements one-by-one faster than just reading array elements?

@xzyfer, I did some tests — using array_filter() just to check if any value is filled is at least few times slower than basic foreach loop with some boolean variable for storing result and break on first invalid value. Even with array_filter() being a «native PHP function», it can’t really be faster than foreach as it has to create new array variable.

i upvoted, still i am a bit surprised this was actually accepted, because it does not fullfill the requirement, does it? If you put say, requestID=0 and status=0 this will result in «please enter a value» when there were clearly values.

Читайте также:  Tkinter for python install

Implode the array with an empty glue and check the size of the resulting string:

Please note this is a safe way to consider values like 0 or «0» as not empty. The accepted answer using an empty array_filter callback will consider such values empty, as it uses the empty() function. Many form usages would have to consider 0 as valid answers so be careful when choosing which method works best for you.

@xzyfer, if $str is (string)’0′ , then strlen($str) == 0 evaluates to false , while !$str evaulates to true , therefore strlen($str) == 0 can’t be replaced with !$str .

@kasimir the callback function of array_filter is optional and the manual clearly states If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed. So, using array_filter is not less correct than this, it’s just a diffrent method 😉

Since the OP provided no sample data and no specific description of what «empty» means and because this page is being used as a canonical, answers should be very careful to provide robust explanations and include caveats where their answers may provide unexpected results. array_filter() and empty() are too often misused/misunderstood by php developers.

An older question but thought I’d pop in my solution as it hasn’t been listed above.

function isArrayEmpty(array $array): bool < foreach($array as $key =>$val) < if ($val !== '' && $val !== null) // remove null check if you only want to check for empty strings return false; >return true; > 

empty() may provide false-positive results. See the manual about how the function treats falsey values. I would recommend the call of strlen() instead.

Thanks for the reminder about falseyness @mickmackusa, I’ve updated it to explicity check for empty string.

you don’t really need it.
You’re going to validate these fields separately and by finishing this process you can tell if array was empty (or contains invalid values, which is the same)

@Capsule for the array size of 6, you will never ever see the slightest difference, even you spend whole your life checking arrays. for the sizes more than 1000 I’d suggest not to use arrays at all.

Since we are talking about websites, you have to multiply that per your number of visitors. An array of 1000 or 100 visitors computing an array of 10 is the same in term of CPU cost. You can’t decide to stop using arrays because your website is gaining some popularity 😉

$array = []; //target array $is_empty = true; //flag foreach ($array as $key => $value) < if ($value != '') $is_empty = false; >if ($is_empty) echo 'array is empty!'; else echo 'array is not empty!'; 

We should see a break in this script. Your answer is missing its educational explanation. This is effectively the same answer as stackoverflow.com/a/38447764/2943403 but a worse version.

I had the same question but wanted to check each element in the array separately to see which one was empty. This was harder than expected as you need to create the key values and the actual values in separate arrays to check and respond to the empty array element.

print_r($requestDecoded); $arrayValues = array_values($requestDecoded); //Create array of values $arrayKeys = array_keys($requestDecoded); //Create array of keys to count $count = count($arrayKeys); for($i = 0; $i < $count; $i++)< if ( empty ($arrayValues[$i] ) ) < //Check which value is empty echo $arrayKeys[$i]. " can't be empty.\r\n"; >> 
Array ( [PONumber] => F12345 [CompanyName] => Test [CompanyNum] => 222222 [ProductName] => Test [Quantity] => [Manufacturer] => Test ) 

Источник

cleanest way to skip a foreach if array is empty [duplicate]

Not a major problem but I was wondering if there is a cleaner way to do this. It would be good to avoid nesting my code with an unnecessary if statement. If $items is empty php throws an error.

$items = array('a','b','c'); if(!empty($items)) < // > 

What? If you just comment out the if you have there, and change the first line to $items = array(); , it works perfectly fine and operates logically. There must be more to your question. Is $items perhaps not an array?

i guess its in case return from function which may return false too. I also have similar problem and i always check using is_array

FYI — «foreach does not support the ability to suppress error messages using ‘@’.` — php.net/manual/en/control-structures.foreach.php — so, no, you couldn’t use @

+1 for strager. If $items is really an array, php won’t give you an error or warning. Check your if/else branches and make sure you initialized variable as an array.

you can find this situation with data coming from a non-trusted function. That case, an if is not unnecessary and it can be even better/cleaner than some other solutions which could be more cryptic and harder to read.

11 Answers 11

There are a million ways to do this.

The first one would be to go ahead and run the array through foreach anyway, assuming you do have an array.

In other cases this is what you might need:

foreach ((array) $items as $item)

Note: to all the people complaining about typecast, please note that the OP asked cleanest way to skip a foreach if array is empty (emphasis is mine). A value of true, false, numbers or strings is not considered empty. In addition, this would work with objects implementing \Traversable , whereas is_array wouldn’t work.

I didn’t get an error when $items undefined. Is this for the old version only? May be new PHP versions took care of this situation?

The best way is to initialize every bloody variable before use.
It will not only solve this silly «problem» but also save you a ton of real headaches.

So, introducing $items as $items = array(); is what you really wanted.

Not if initializing from a function/method. $items = get_stuff() . It’s easier just to cast and falsy variables return an empty array.

get_stuff() may come from an external API. It’s not uncommon for library functions to return Array|NULL

Even phps own functions return different types. Assume you request some JSON array over the network. You know that the produced JSON is always an array. So json_decode() will always return an array? No. A network timeout might occur, the received JSON will be incomplete and json_decode will return NULL. This is not made up, its a real life example taken from a recent bug in piwik, a popular analytics script: github.com/piwik/piwik/pull/11098 From your answer, the solution would have been to change php’s json_decode()?

@YourCommonSense where is your answer doing any validation? Validating would mean e.g. checking whether what json_decode() returned is an array, which is exactly what the answer of Matt Williamson says.

@YourCommonSense The solution you describe is of course correct. But your original answer does not mention that and how to validate the input. It might even lead some people to false assumptions, like thinking this is safe just because initialization was used: $items=array(); $items=json_decode($str); foreach($items as $item).

$items = array('a','b','c'); if(is_array($items)) < foreach($items as $item) < print $item; >> 

+1 this way if $items is array but is empty, the foreach will not run and there will be no error. but empty() doesn’t guarantee if $items is an array, so an error is possible

If variable you need could be boolean false — eg. when no records are returned from database or array — when records are returned, you can do following:

foreach (($result ? $result : array()) as $item) echo $item; 

Approach with cast( (Array)$result ) produces an array of count 1 when variable is boolean false which isn’t what you probably want.

This will produce a syntax error when assigning by reference, as in «foreach. as &$item», because when $result is null it can’t assign a reference to «array()». See: php.net/manual/en/control-structures.foreach.php

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. So it may become foreach (($result ?: array()) as $item) . And if $result may be null , then php 7 introduced null coalescing operator foreach (($result ?? array()) as $item) . See php.net/manual/en/language.operators.comparison.php

I wouldn’t recommend suppressing the warning output. I would, however, recommend using is_array instead of !empty . If $items happens to be a nonzero scalar, then the foreach will still error out if you use !empty .

I hat the is_[array] function, this sound like a poor programming still. Let me explain why: Why asking that a variable is an array? You should know that is an array otherwise it mean that you are messing with the type of the variable. If your type is getting inconsistent you are looking for trouble. When you start using the is_* function it tend to be spread all over your code. And after all you never know if the is_* is necessary and your code is being unreadable. I suggest you to fix the origin of the type inconsistency instead.

@mathk You probably come from strongly typed language. PHP variable can store anything, that’s why is_array, is_numeric, etc are needed functions.

Источник

PHP Foreach loop if field is not empty

I am trying to master the art of the foreach loop; I have the following code which I am using with WordPress and the Advanced Custom Fields pluging. I want to turn it into a foreach loop.

">">">">">

I have tried writing the code below but it doesn’t work, and I don’t know how to limit the loop to 5 (images). Note that get_field returns the image url whilst the_field returns the image.

5 Answers 5

If you know that there are only 5 items, then you would just use a for or while loop. foreach is a loop designed for looping through an array of elements, which you don’t have.

Consider this loop instead:

for($i = 1; $i '; echo ''; echo ''; > >

foreach is used to iterate over arrays, e.g.

foreach (array_expression as $value) < // current array element >

The syntax you’re using will not work with foreach (see examples to understand how it works).

For the implementation you posted, you would be better off using a normal for loop.

To use a foreach loop, you need to have iterate over an array. get_field(«name») does not return an array, however you CAN use foreach with get_fields()

$fields = get_fields(); if( $fields ) < foreach( $fields as $field_name =>$value ) < // Output values here >> 

In your case for loop is better as changed in the loop value is numeric. So solution will be like:

for ($i = 1; $i', $src); printf('', $src); print(''); >

If you still want to use foreach loop then you can use built-in php function range to get required numbers.

foreach (range(1, 5) as $i) < $src = the_field('image_'.$i); printf('', $src); printf('', $src); print(''); >

What you probably wanted to write was a while loop up there. Foreach loops don’t test a condition before a cycle. Rather, foreach loops take an array and iterate over all the values within. It can also iterate over associative arrays.

 'John Doe', 'user_2' => 'Jacob Doe', 'user_potato' => 'Jane Doe' ); foreach ($users as $user_id => $name) < echo $user_id, ' - ', $name, '
'; >
user_mango - John Doe user_2 - Jacob Doe user_potato - Jane Doe 

I’m not a wordpress developper but if you wanted to write this code in the style you started off with, here goes:

while loops, unlike foreach loops, test a condition before each iteration. Here in the above example code, we have our counter variable initialized to zero. Inside the loop we increase the counter variable by one on each iteration, and in the condition, we specify that in order for the full expression to be true the counter must be smaller than 5.

Источник

Оцените статью