given I have an array, say:
$myArray=['12','AB','3C']
I want to return the value 2 (which is the length of each of the array elements indivudually.)
But in case I have something like
$myArray=['12','AB2','3C']
I want to stop the calculation/loop right after the second element of the array 'AB2'
and let my function return null.
What is the most effective way to reach this in the matter of being performance and speed effective? Since such an array can get long.
I think you are trying to stop the array loop the moment you get two different lengths in an element?
In that case, at worst, you'd need an O(n)
runtime (since you need to verify every element, unless you have an abstract data type in mind in which case it could be O(1)
, if it is stored in the object property or you calculate the difference detected on the fly while pushing items into arrays)
Since the moment we discover an element is not the same length, we can simply quickly store the length of the first element in the array since we know if we detect any other length other than what we stored, we can immediately return null
function linear_loop($array) {
$len_of_first = strlen($array[0]);
foreach ($array as $val) {
if (strlen($val) != $len_of_first) {
return null;
}
}
//Function still running, entire array was same, return the length of first element
return $len_of_first;
}
This function is O(n)
with each operation is constant. strlen
is O(1)
Algorithmic complexity of PHP function strlen()
Since you said that the array can get quite long, if you are not immediately generating the array, but rather you need to push items into it, then in your push operation, you can check before pushing it the item_to_be_pushed
is the same strlen
or whatever property you are trying to compare as the one you've stored (which can be picked arbitrarily, since the array must be of uniform some property
)
In this case, you could have some object
with property
: uniform_length
and store that. Then whenever you push
into your array, you can check against it with the uniform_length
. If it isn't the same length, then you can store in the object property called uniform
as false. (By default uniform
is true since if there is only one element in the array, it must be uniform).
This would be an O(1)
calculation since it is stored as an attribute. But you probably don't need an object for something as simple as this, and you can just store it as some variable.
Since not everyone knows Big O, a quick explanation on what I said. O(1)
runtime is "infinitely" better than O(n)
runtime since the runtime of the function will not grow with input (as in processing 1 million items require the same amount of steps as processing 1 item)