Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is a better way to check if an array has more than one element?

Tags:

arrays

php

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?

like image 597
tuxnani Avatar asked Apr 05 '12 08:04

tuxnani


People also ask

How do you check multiple elements in an array?

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 .

How do you check if an array has only one element?

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.

Can array contain more than one element?

Explanation: Array will have many elements with same data type.

How do you check if all array elements are the same?

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.


1 Answers

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.

like image 125
Chibuzo Avatar answered Oct 21 '22 15:10

Chibuzo