I just need to check if an array has more than one element. I am trying to do it this way :
if (isset($arr['1']))
the other traditional way is
if (sizeof($arr)>1)
Which of the two is better? In such situaions, how should I judge between two alternate methods? Is there any performance check meter available to measure which is better?
To check if multiple values exist in an array:Use the every() method to iterate over the array of values. On each iteration, use the indexOf method to check if the value is contained in the other array. If all values exist in the array, the every method will return true .
Assume the first element of the array to be the only unique element in the array and store its value in a variable say X. Then traverse the array and check if the current element is equal to X or not. If found to be true, then keep checking for all array elements.
Explanation: Array will have many elements with same data type.
To check if all values in an array are equal:Use the Array. every() method to iterate over the array. Check if each array element is equal to the first one. The every method only returns true if the condition is met for all array elements.
Use this
if (sizeof($arr) > 1) { .... }
Or
if (count($arr) > 1) { .... }
sizeof()
is an alias for count()
, they work the same.
Edit: Answering the second part of the question: The two lines of codes in the question are not alternative methods, they perform different functions. The first checks if the value at $arr['1']
is set, while the second returns the number of elements in the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With