-1

I have two variables: $value1 and $value2.

I want to compare the character length of the variables. If $value1 is greater in character length than $value2, then do something.

How can I write this if-statement in good practice?

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155

3 Answers3

2

You can use strlen() for this:

if (strlen($value1) > strlen($value2)) {
    // do things
} else {
    // do other things
}
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • [`Indeed`](http://stackoverflow.com/questions/26531526/if-statement-to-compare-character-length-of-variables-in-php#comment41689387_26531526), said as a comment. Doing a conditional's easy. – Funk Forty Niner Oct 23 '14 at 15:24
  • Uhms, I didn't see it @Fred-ii- . Feel free to post as an answer and I will remove the answer. – fedorqui Oct 23 '14 at 15:25
  • 2
    @fedorqui Why should you remove it? This is a complete answer compared to the comment which was only a comment hinting at the solution. – Henrik Petterson Oct 23 '14 at 15:26
  • 1
    I didn't want to post an answer for it. I feel that answers shouldn't be posted for questions like this, unless OP has existing problems with code he/she tried. I'm sure that if I had done that, some of my peers would have most likely downvoted me. – Funk Forty Niner Oct 23 '14 at 15:26
  • 1
    @HenrikPetterson It's a simple conditional statement, something that is basic. Googling it would have given you many many options for solutions. I don't think this question is a good one, since you haven't provided any effort as far as code goes. There was even a solution/example in that link I gave you. – Funk Forty Niner Oct 23 '14 at 15:29
  • 1
    Well, [so] is full of obvious questions and answers. If it happens to have been already asked, then let's mark it as duplicate; otherwise, I do not see the harm of answering it. It adds knowledge to the site. – fedorqui Oct 23 '14 at 15:45
1

strlen does not work for multi byte strings. utf8 is pretty much the most used encoding in the WWW.

Better use mb_strlen instead:

mb_internal_encoding('UTF-8');
$value1 = 'ö';
$value2 = 'o';
if (mb_strlen($value1) > mb_strlen($value2)) {
    //do something
}
BreyndotEchse
  • 2,192
  • 14
  • 20
1

To avoid problems with string enconding I would suggest you to have a look at mb_strlen function (you will need mb_string extension)

if (mb_strlen($value1) > mb_strlen($value2))
{
   // do stuff
}
PauloASilva
  • 1,000
  • 1
  • 7
  • 19