PHP string comparison for strpos strcmp

220
July 08, 2017, at 1:34 PM

I'm using PHP 7.0 and I want to do only string comparison. PHP has strpos strcmp function to do that but I don't know which function will be fast and safe to do string comparison. I have to compare a lot of string and I want to know which function would bring faster result.

In my test, strpos doesn't return NULL for array string comparison but strcmp does. In PHP 7 I tested, but I may use other PHP version for hosting and this problem will be sensitive. Is okay to use if (strpos($x, $y)) to use string comparison?

Answer 1

strpos — Find the position of the first occurrence of a substring in a string

strcmp — Binary safe string comparison

If the string is a string of text like you would get from user input or anything that is not binary then strcmp seems overkill. I would use Difster's suggestion; It read cleaner then if (strcmp($a,$b))

mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

This is the method signature for strpos will the return a truthy value if $b is in $a. So i would not use it to compare if two string are equal only if you want to see if a string is inside another or want to know where the string is at inside the other.

READ ALSO
How to create unique entry in database for new userId?

How to create unique entry in database for new userId?

I have customer table where I wanted to store a customer with a cusomerNumber Like

123
Exclusive Consumption of Messages in PhpAMQPLib/RabbitMQ

Exclusive Consumption of Messages in PhpAMQPLib/RabbitMQ

I am publishing multiple tasks (messages) to a queue, and I want multiple workers (consumers) to handle the tasks, but each task must be handled by only one workerHowever when I start two workers and listening to the same queue, both of them receive the same task

133
How can I use PHP in html to take user input and make a new page or listing? [on hold]

How can I use PHP in html to take user input and make a new page or listing? [on hold]

I am trying to make a web form for my website (still not live) that allows users to add listingsSuch as a craigslist, airbnb or anything else like that

115