How do I find if an array has one or more elements?
I need to execute a block of code where the size of the array is greater than zero.
if ($result > 0) {
// Here is the code body which I want to execute
}
else {
// Here is some other code
}
You can use the count()
or sizeof()
PHP functions:
if (sizeof($result) > 0) {
echo "array size is greater than zero";
}
else {
echo "array size is zero";
}
Or you can use:
if (count($result) > 0) {
echo "array size is greater than zero";
}
else {
echo "array size is zero";
}
count
— Count all elements in an array, or something in an object
int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )
Counts all elements in an array, or something in an object.
Example:
<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
// $result == 3
In your case, it is like:
if (count($array) > 0)
{
// Execute some block of code here
}
You could avoid length retrieve and check using a simple foreach:
foreach($result as $key=>$value) {
echo $value;
}
If you want to only check if the array is not empty, you should use empty()
- it is much faster than count()
, and it is also more readable:
if (!empty($result)) {
// ...
}
else {
// ...
}
@Sajid Mehmood in PHP we have count() to count the length of an array,
when count() returns 0 that means that array is empty
Let’s take an example for your understanding:
<?php
$arr1 = array(1); // With one value which will give 1 count
$arr2 = array(); // With no value which will give 0 count
// Now I want that the array which has greater than 0 count should print other wise not so
if (count($arr1)) {
print_r($arr1);
}
else {
echo "Sorry, array1 has 0 count";
}
if (count($arr2)) {
print_r($arr2);
}
else {
echo "Sorry, array2 has 0 count";
}
For those who start with the array in PHP presented it this way:
more information here
//Array
$result = array(1,2,3,4);
//Count all the elements of an array or something of an object
if (count($result) > 0) {
print_r($result);
}
// Or
// Determines if a variable is empty
if (!empty($result)) {
print_r($result);
}
// Or
// sizeof - Alias of count ()
if (sizeof($result)) {
print_r($result);
}
Pro Tip:
If you are sure that:
- the variable exists (isset) AND
- the variable type is an array (is_array) ...might be true of all is_iterables, but I haven't researched that extension of the question scope.
Then you don't need to call any functions. An array with one or more elements has a boolean value of true
. An array with no elements has a boolean value of false
.
Code: (Demo)
var_export((bool)[]);
echo "\n";
var_export((bool)['not empty']);
echo "\n";
var_export((bool)[0]);
echo "\n";
var_export((bool)[null]);
echo "\n";
var_export((bool)[false]);
echo "\n";
$noElements = [];
if ($noElements) {
echo 'not empty';
} else {
echo 'empty';
}
Output:
false
true
true
true
true
empty
<pre>
$ii = 1;
$arry_count = count($args);
foreach ( $args as $post)
{
if( $ii == $arry_count )
{
$last = 'blog_last_item';
}
echo $last;
$ii++;
}
</pre>