$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?
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.
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.
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.
The length returns the number of elements that a dense array has.
A couple other options:
Use the comma operator to create an array:
$cars = ,"bmw" $cars.GetType().FullName # Outputs: System.Object[]
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")
Instead of writing echo $cars.length
write echo @($cars).length
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