Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count length of array and return 1 if it only contains one element

$cars = "bmw","audi","volvo","vw" echo $cars.length 

returns 4, but

$cars = "bmw" 

returns 3 because it counts the characters..

Is there a way I can return 1 if the array only contains one item?

like image 986
Sune Avatar asked Mar 06 '12 08:03

Sune


People also ask

How do you count elements in an array?

You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn't set.

What is meant by array length 1?

length -1 means, specifically the -1 part. When using a for loop over an array we have something like this: for (i = 0; i < array.

Does array length count from 0 or 1?

Arrays in JavaScript are zero-based. This means that JavaScript starts counting from zero when it indexes an array. In other words, the index value of the first element in the array is “0” and the index value of the second element is “1”, the third element's index value is “2”, and so on.

What does .length do in an array?

The length returns the number of elements that a dense array has.


2 Answers

A couple other options:

  1. Use the comma operator to create an array:

    $cars = ,"bmw" $cars.GetType().FullName # Outputs: System.Object[] 
  2. Use array subexpression syntax:

    $cars = @("bmw") $cars.GetType().FullName # Outputs: System.Object[] 

If you don't want an object array you can downcast to the type you want e.g. a string array.

 [string[]] $cars = ,"bmw"  [string[]] $cars = @("bmw") 
like image 80
Andy Arismendi Avatar answered Nov 04 '22 23:11

Andy Arismendi


Instead of writing echo $cars.length write echo @($cars).length

like image 40
jon Z Avatar answered Nov 05 '22 00:11

jon Z