Problem:
Suppose you have an optional form field (declared as an array, see the following code) which may accept nothing or one or multiple values from a user. Now, you want to check if the user has added anything at all in the form field
<input name=”mobile[]” type=”text” />
Solution:
You can do it in few ways. Here, you’ll see two ways-
Method 1: Using empty() function
You can use count() function to get to know if the array is empty or not. An empty array is considered as empty and the function count() returns true if the value is empty. See it in action in the following example-
<?php $mobile1 = array(); echo empty($mobile2) ? "Array is empty.": "Array is not empty."; echo "<br />"; $mobile2 = array('760-987-0000','760-987-1111','760-987-2222'); echo empty($mobile2) ? "Array is empty.": "Array is not empty."; ?>
[wpdm_file id=72]
Output:
Array is empty.
Array is not empty.
How it works:
As $mobile1[] array has no value, so empty($mobile1) returns true and prints “Array is empty.”. On the other hand, mobile2[] array has 3 values. So empty($mobile2) returns false and prints “Array is not empty.”.
Method 2: Using count() function
You can also calculate number of elements in the array. If the array is an empty array, the function will return 0 otherwise it will return number of elements. See the example below-
<?php $mobile = array();echo (count($mobile) == 0) ? "Array is empty.": "Array is not empty."; echo "<br />"; $mobile = array('760-987-0000','760-987-1111','760-987-2222'); echo (count($mobile) == 0) ? "Array is empty.": "Array is not empty."; ?>
Output:
Array is empty.
Array is not empty.
[wpdm_file id=71]
How it works:
As $mobile1[] array has no value, so count($mobile1) is equal to 0 and prints “Array is empty.”. On the other hand, mobile2[] array has 3 values. So count($mobile2) returns 3 and prints “Array is not empty.”.