if ( strlen( $unknownString ) > 10 ) { echo "String has more than 10 characters"; }
PHP Coding tips & tricks. Function & error explanation, coding style, how tos etc. Short notes posted directly from developer work environment.
PHP Coding Tips
Showing posts with label string. Show all posts
Showing posts with label string. Show all posts
Monday, August 13, 2012
How to measure length of a string ?
If you want to check a length of the string in php, just user strlen() function. It will return the given string length. See example:
Wednesday, August 8, 2012
How to check that one string contains another in PHP
If you want to check if one string contains desired string, you can use strpos function. But be aware - the problem rises when a needle is on position 0 of checked string. In that situation php strpos() returns 0, and it will return false if string is not found. So, to compare if a string is containing user string, use !== operator
if ( strpos( $string , 'somestring' ) !== false ) {
}Also use === false if you want to check that string doesn't not contains data
Tuesday, August 7, 2012
How to split an array to parts by comma or special character (string to array) ?
Use explode function for this job:
$names = 'John,Margaret,Thomas';
$namesArray = explode( ',' , $names );
echo $namesArray[0];
echo $namesArray[1];
echo $namesArray[2];You can also use a character sequence to split string like a "splitplace"
How to convert string to int, or other variable to integer
To convert string to int in PHP you can use casting or intval() function. See example:
$intVariable = intval( $unknownVariable );
// or:
$intVariable = (int)$unknownVariable;You can cast with this function every php variable, like double. Remember that php can throw a error or warning, especially if variable is not set
Subscribe to:
Posts (Atom)