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
}
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 {
// ...
}
You could avoid length retrieve and check using a simple foreach:
foreach($result as $key=>$value) {
echo $value;
}
#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";
}
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
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);
}
<pre>
$ii = 1;
$arry_count = count($args);
foreach ( $args as $post)
{
if( $ii == $arry_count )
{
$last = 'blog_last_item';
}
echo $last;
$ii++;
}
</pre>
Related
I'm trying to find a native php function which returns true if there is exactly one occurrence of any given element in an array.
For example:
$searchedForValue = 3;
$array1 = [1,2,3,4,5,6];
$array2 = [1,2,3,3,4,5];
$array3 = [1,2,4,5,6];
oneOccurrence($array1,$searchedForValue);
oneOccurrence($array2,$searchedForValue);
oneOccurrence($array3,$searchedForValue);
This should return:
true
false
false
Cheers
You should use array_count_values() here.
$array_values = array_count_values($array2);
This will return an array. Key denotes each element of $array2 and value denotes frequency of each element.:
Array (
[1] => 1
[2] => 1
[3] => 2 // Denotes 3 appears 2 times
[4] => 1
[5] => 1
)
if (#$array_values[$searchedForValue] == 1) {
echo "True";
} else {
echo "False";
}
This does what you want. Bare in mind, echoing oneOccurence won't output 'true' or 'false', it returns a boolean.
function oneOccurrence ($arr, $val) {
$occurrences = [];
foreach ($arr as $v) {
if ($v == $val) {
$occurrences[] = $v;
}
}
return count($occurrences) == 1;
}
P.S echo doesn't need brackets as it's a PHP construct.
A small utility function - count array values using array_count_values and then if the search key exists and if its count is exactly 1, return true otherwise false:
function oneOccurrence($array, $searchValue) {
$array = array_count_values($array);
return (array_key_exists($searchValue, $array) && $array[$searchValue]==1)?true:false;
}
Check EVAL
Since you are searching for one occurrence: http://codepad.org/cZImb4FI
Use array_count_values()
<?php
$searchedForValue = 3;
$array1 = array(1,2,3,4,5,6);
$array2 = array(1,2,3,3,4,5);
$array3 = array(1,2,4,5,6);
$arr = array($array1,$array2 ,$array3);
function array_count_values_of($value, $array) {
$counts = array_count_values($array);
return $counts[$value];
}
foreach($arr as $ar){
if( array_count_values_of($searchedForValue,$ar)==1){echo "true";}else{echo "false";}
}
?>
output
true false false
//In Php in_array() function is provided..
$searchedForValue = 3;
$array1 = array(1,2,3,4,5,6);
$array2 = array(1,2,3,3,4,5);
$array3 = array(1,2,4,5,6);
if(in_array($searchedForValue,$array1))
{
echo "true";
}
else
{
echo "false";
}
if(in_array($searchedForValue,$array2))
{
echo "true";
}
else
{
echo "false";
}
if(in_array($searchedForValue,$array3))
{
echo "true";
}
else
{
echo "false";
}
I tried this:-
function sum_array($arr_sum){
$string= "";
$length= count($arr_sum);
$sum= NULL;
if(is_string($arr_sum)){
echo "You cannot use string";
}else{
for($i=0; $i<$length; $i++){
$sum = $sum + $arr_sum[$i];
}
echo " The Sum is ". $sum;
}
}
$array_summation=["string",12.6,25.2,10,12];
sum_array($array_summation);
I want to know what should i do if i want only integer or float value inside an array, and if string come inside array it gives error that no string wanted or something like that
Use array_map to get the type of each value present in the array -
$type = array_map('gettype', $array_summation);
if (!empty($type) && in_array('string', $type) {
echo "You can't use string.";
}
Try this
function sum_array($arr_sum){
$sum = 0;
foreach($arr_sum as $value){
if(!is_numeric($value)){
echo 'Array Contain non numeric data';
exit;
}
$sum += $value;
}
echo 'The sum is '.$sum;
}
$array_summation=["string",12.6,25.2,10,12];
sum_array($array_summation);
PHP has a built-in array_sum function, which ignores non-numeric strings.
$arr = [1,2,'3','apple'];
var_dump(array_sum($arr)); // int(6)
Or if you really need them to produce an error you can use array_map:
function sum_array($arr) {
if (array_sum(array_map('is_numeric', $arr)) !== count($arr)) {
echo "You cannot use string";
return;
}
echo array_sum($arr);
}
sum_array([1,2,'3','apple']); // You cannot use string
sum_array([1,2,'3','5.2']); // 11.2
Or if you want to make sure that all values in the array are either floats or integers, and not numeric strings, you can do:
function is_non_string_number($n) {
return is_float($n) || is_int($n);
}
function sum_array($arr) {
if (array_sum(array_map('is_non_string_number', $arr)) !== count($arr)) {
echo "You cannot use string";
return;
}
echo array_sum($arr);
}
sum_array([1,2,'3','apple']); // You cannot use string
sum_array([1,2,'3','5.2']); // You cannot use string
sum_array([1,2,3]); // 6
I'd like my function to have a comparison operator as an argument (or preferably, as part of an argument such as >0 ):
Instead of
function comps($a,$b){
if ($a > $b)
echo "This works.";
}
comps(1,0);
I'd like to be able to do something like
function comps($a,$b){
if ($a $b)
echo "This works.";
}
comps(1,'>0');
I've been banging my head agains the wall on this for a while. I've tried different iterations of:
"/>0"
'>' . 0
(string)> 0
as well as trying the comparison operator as a third argument.
Actual use is:
function mysort($key,$match){
$temp_array = array();
global $students;
foreach ($students as $row) {
if($row[$key] > $match )
$temp_array[]= $row;
}
foreach ($temp_array as $row) {
echo $row['email'] . ', ';
}
}
mysort('suzuki', '0');
Thanks
You can make a return type function and use as you want.
I'll Make a function to you as Below:
<?php
function getCond($a, $b, $both) {
$data = false;
if($both) {
if($a == b) {
$data = true;
}
}else {
if($a > $b) {
$data = true;
}
}
return $data;
}
/* Use Your Function */
if (getCond(10, 5, true)) { // condition for 10 == 5 and according to passed values you get false result in condition
echo "you result";
} else if (getCond(10, 5, false)) { // condition for 10 > 5 and according to passed values you get false result in condition
echo "your result";
} else if (getCond(6, 5, false)){ // condition for 6 > 5 and according to passed values you get true result in condition
echo "your result";
}
?>
You also can modify this function as you want :)
The simplest solution for my use seems to be:
function comps($a,$b,$c){
if ($a > $b and $a < $c)
echo "True";
}
comps(1,0,2);
?>
If I have an array:
$nav = array($nav_1, $nav_2, $nav_3);
and want to check if they are empty with a loop (the real array is much bigger), so that it checks each variable separately, how do I do it?
I want something like this;
$count = 0;
while(count < 3){
if(empty($nav[$count])) //the loops should go through each value (nav[0], nav[1] etc.)
//do something
$count = $count+1;
}else{
//do something
$count = $count+1;
}
}
Pretty straight-forward with a foreach loop:
$count = 0;
foreach ($nav as $value) {
if (empty($value)) {
// empty
$count++;
} else {
// not empty
}
}
echo 'There were total ', $count, ' empty elements';
If you're trying to check if all the values are empty, then use array_filter():
if (!array_filter($nav)) {
// all values are empty
}
With the following code you can check if all variables are empty in your array. Is this what you are looking for?
$eachVarEmpty = true;
foreach($nav as $item){
// if not empty set $eachVarEmpty to false and go break of the loop
if(!empty(trim($item))){
$eachVarEmpty = false;
// go out the loop
break;
}
}
$empty = array_reduce($array, function(&$a,$b){return $a &= empty($b);},true);
I was wondering how can I check if an array is empty or not in a function
Here is part of my code.
if (!mysqli_query($dbc, $sql)) {
trigger_error(mysqli_error($dbc));
return;
} else {
$t = array();
while($row = mysqli_fetch_array($result)) {
$t[] = $row[0];
}
}
if($tr > 0){
$ts = array_sum($t);
}
Use the empty() function:
http://php.net/manual/en/function.empty.php
Loose equivalency checking returns false on an empty array
if(array()) // returns false
http://php.net/manual/en/types.comparisons.php
Use count() to count the number of elements in the array.
An easy method would be to use the count function.
For example:
if(count($sourceArray) != 0) {
// Do exciting things here...
}
empty($t);
gives you true if $t is considered empty.
To check if array is empty:
if (sizeof($arr) == 0)
{
//Empty array
}
To check whether an element exists in an array or not:
if (in_array($element, $arr))
{
//Element found in the array
}