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
https://forums.phpfreaks.com/topic/285933-a-basic-question-about-functions/
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';
}

@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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.