Reputation: 1437
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
Upvotes: 0
Views: 7502
Reputation: 48049
Thinking outside of the box, your task appears to want to validate that no values have been added beyond the delimiting character sequences. For this reason, you don't actually need to produce an array, then check that array. Instead, just check if the input string is fully comprised of your delimiting sequences.
Code: (Demo)
$address = "#&#&#&";
$delimiter = '#&';
if (preg_match('~^(?:' . preg_quote($delimiter) . ')+$~', $address)) {
echo 'Text comprised solely of one or more delimiting substrings';
}
In truth the preg_quote()
call is not actually needed, I just thought it would make the answer more robust for general use. The pattern can simply be /^(?:#&)+$/
.
Upvotes: 0
Reputation: 3847
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
}
Upvotes: 2
Reputation: 3368
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';
}
Upvotes: 0
Reputation: 212522
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
Upvotes: 6
Reputation: 10563
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;
}
}
Upvotes: 1
Reputation: 66825
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";
Upvotes: 1