M477HEW Posted May 20, 2009 Share Posted May 20, 2009 I'm really new to PHP and am currently using the framework of an existing site to help me learn the ropes. I have the following line of code and I'm kind of stuck. I'm OK up to the ['long_descr'] but after that I am lost. Can anyone help me out and explain this line of code to me please? I'm particularly confused by the last half - ,0,20 etc. What do these numbers represent? $index=strpos(substr($data[0]['long_descr'],0,20),'same_as'); Thanks in advance for any help Matt Quote Link to comment https://forums.phpfreaks.com/topic/158985-indexstrpossubstrdata0long_descr020same_as/ Share on other sites More sharing options...
Masna Posted May 20, 2009 Share Posted May 20, 2009 Ever heard of the manual? http://php.net/substr Quote Link to comment https://forums.phpfreaks.com/topic/158985-indexstrpossubstrdata0long_descr020same_as/#findComment-838468 Share on other sites More sharing options...
eRott Posted May 20, 2009 Share Posted May 20, 2009 For beginners, even the documentation can be confusing. First off, let's break it down. The line of code you posted uses two functions. strpos() and substr(). The strpos() function is used to find the first occurrence of a string within another string. Take the below as an example. The resulting value of the variable $pos would be 0 because a is the very first character in the string (it starts at 0, not 1). $mystring = 'abc'; $findme = 'a'; $pos = strpos($mystring, $findme); The substr() function returns a specific section of a string which you tell to find by providing where in that string to start and where to end. Take the below code as an example. The resulting value of $return would be Hello because you are telling it to return only the part of the string starting from 0, (the beginning), and ending at 4, (the letter "o" is in the fourth position where the letter "H" would be position zero). $mystring = 'Hello my name is Matt!'; $return = substr($mystring, 0, 4); With that in mind, the line of code you posted grabs the first 21 characters of a string which is, from the looks of it, a description of something ($data[0]['long_descr']). (Note, spaces count as a character). It then searches for the first occurrence of "same_as" in that string and stores the position of that first occurance in the variable $index. The following bit of code make make it a little easier to read. $haystack = substr($data[0]['long_descr'],0,20); $index = strpos($haystack,'same_as'); Correct me if I am wrong, but I am fairly certain that is what that line of code does. Quote Link to comment https://forums.phpfreaks.com/topic/158985-indexstrpossubstrdata0long_descr020same_as/#findComment-838498 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.