Sun, 5 May 2024


PHP Strpos Function

By: Anton, NetArt Media
Wed, 1 August 2018
PHP Strpos Function

Question/answer sessions and interviews are quite popular on the internet, especially within the entertainment industry. Looking at that, I thought I would create a fake interview excerpt using a string with the information 'Jan' has provided. From the $intro string, I then use the strpos function to find certain words contained within it and return some of the information accordingly.


Strpos finds the word 'two' in the string, str_replace changes it to the digit '2' and substr is used to locate the actual position and then I created an answer to echo out according to the interviewer's question. I included the additional functions to show you how they can work well together.

Here is the result of the above code block...

Question: How many places in the world would you like to visit the most?
Answer: 2

Now, let's expand on the interview a little bit.


Strpos now searches for the words 'Russia and Chile', whereby, I then create a Conditional Statement which defines what Jan's answer will be based on the interviewer's question. Her answer, in this case, would of course be 'Yes'. If we were to change 'Russia and Chile' to say...'Canada and Mexico', her answer would be 'No'.

Now let's look at finding a specific value in an array using the PHP strpos function.


There are several ways of dealing with finding 'needles' in an array 'haystack'. I kept this particular code block simple, however. Sometimes I will create a function to search inside an array for particular information, but more often than not, I like to turn the 'needle' into a simple variable, using strpos to find it and returning whatever result I desire.

Seeing that the number '2' is not in the stats array within our code above, the result of course will be..

The number 2 is not in the statistics array.

If we were to change $var to either 1, 3, 5, 7 or 9, we would of course get a positive result. This particular piece of code would work great if $var came from a database or an HTML form. We would have an immediate variable available to search through the array with.

These examples are very basic samples of how to use the PHP strpos function, however, they do supply almost everything you need to know for using it. It's a great function, very powerful when used in conjunction with others, as well as within Conditional Statements.

I hope this PHP function tool box tutorial has been helpful to you. There are many more to come.


Category: Web Development
Share this post:



See All Scripts






Subscribe for our newsletter

Receive the latest blog posts direct in your mailbox