Jump to content

A basic question about functions


Zola

Recommended Posts

Hi

 

I am learning PHP on codecademy at the moment. Enjoying it well and going right back to the basics to try to get a fundamental understanding

 

At the moment, I am learning about functions (strlen, strpos) etc. etc.

 

This may be a stupid question, but can anyone please give me a real world example of where these functions may be used?

 

I guess strlen could be used to allow or disallow a certain length of a user name or something, but what use would strpos have?

 

 

Link to comment
Share on other sites

strlen returns the length of the string you pass to it. You could use this as you mentioned to check a username matches a certain length.

if(strlen($username) < 5) {
   echo 'Your username is too short. 5 Characters minimum';
}

strpos is used for finding the position of a character within a string. A weak example of this would to check if an email address is valid by checking for the @ char

if(strpos($emailAddress, '@') === false) {
   echo 'Your email address is invalid';
}
Edited by Ch0cu3r
Link to comment
Share on other sites

@Ch0cu3r, but...not in a situation where the string contains non-english characters :)

<?php

// $username = "jazz"; 

$username = 'джаз'; // cyrillic characters

if(strlen($username) < 5) {
   echo 'Failed';
} else {
   echo 'Past';     
}

 In case like this, he would consider using Multibyte String Functons expecialy mb_strlen and mb_strpos.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.