I am trying to see if a string is over 10,000 characters. if it is, it should print too long
. I know I can do this with strlen
, but then the time complexity is O(n)
, which, isn't too bad, but I still have to iterate through 10,000 characters every time if someone enters 10,000 characters, but if my someone enters 1 million characters, thats a bad n
. So My solution is, to check if the 10,001th character is set. If it is set, then its obviously too long. Would this work? Or would this sometimes work (and depends on how memory was/is being allocated).
Asked
Active
Viewed 284 times
1

Yuri
- 89
- 1
- 1
- 9
4 Answers
1
I know I can do this with strlen, but then the time complexity is O(n)
I don't know who tell you this, strlen
is simply returns the len
property.
Definition of strlen, it use ZSTR_LEN
macro to get the string length
ZEND_FUNCTION(strlen)
{
zend_string *s;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STR(s)
ZEND_PARSE_PARAMETERS_END();
RETVAL_LONG(ZSTR_LEN(s));
}
And the definition of ZSTR_LEN
#define ZSTR_LEN(zstr) (zstr)->len

shingo
- 18,436
- 5
- 23
- 42
-
I was taught in `c`. And I've been told that in `c` `strlen` is O(n). I assumed it would be the same in `php` – Yuri Jan 24 '19 at 22:49
0
<?php
if (isset($str[100001])) {
... do my stuff ...
} ?>
The isset function is run on $str[10001] which is only one address in the array, hence o[1]. Also, while accessing key out of index in php, it does not throw error or cause memory leak. It throws an OutOfBoundsException exception which can be caught with a try catch block.

Aakash Gandhi
- 55
- 5
-
-
@AbraCadaver, the isset function is run on $str[10001] which is only one address in the array, hence o[1]. Also, accessing array out of index within isset function does not throw any error. – Aakash Gandhi Jan 24 '19 at 03:05
-
What about memory allocation? Would the result be affected? For example, if the string is only 250 characters long, and we look for the 10001 character, there might be something there in memory (garbage data) – Yuri Jan 24 '19 at 03:06
-
@Yuri, Actually if you have the code in a try block, php will throw an OutOfBoundsException provided you catch it. Nothing is added in the memory. Have a look into this - https://stackoverflow.com/questions/8193798/outofrangeexception-vs-outofboundsexception – Aakash Gandhi Jan 24 '19 at 03:18
-
I know the explanation, add it to the answer, not just _This might work._ – AbraCadaver Jan 24 '19 at 16:04
0
strlen
already has a time complexity of O(1), due to the fact that length is simply stored as an attribute.

Icehorn
- 1,247
- 8
- 15