How long is a piece of $string.... too long... php - php

what am I doing wrong here guys?
$string = "string How Long is a Piece of String?";
if $string = <5;
{
echo "string is less than 5";
}
else
{
echo "string is more than 5";
}

1st, condition are in parenthesis.
2nd, you don't need a ; after a condition.
3rd, less than is simply < not <= unless you want to echo "string is less or equals than 5"
$string = "string How Long is a Piece of String?";
if (strlen($string) < 5)
{
echo "string is less than 5";
}
else
{
echo "string is more than 5";
}

Others pointed out the syntax errors, to actually compare to the length of the string you need to use the strlen function:
$string = "string How Long is a Piece of String?";
if (strlen($string) < 5)
{
echo "string is less than 5";
}
else
{
echo "string is more than 5";
}

Type juggling it is called:
http://nl2.php.net/manual/en/language.types.type-juggling.php
$string = "string How Long is a Piece of String?";
if ($string < 5)
string is cast to int, becomes 0
if (0 < 5)
true!
strlen / mbstrlen are possible candidates you're loking for
But that wasn't the question, there are obivously more things wrong with the code :)

may be you're looking for the strlen() function?

missing parentheses around if statement and no need for semi-colon? also less than or equal operator in wrong order. should be like this:
if ($string <=5)
{
echo "string is less than 5";
}

Also note that if that string has multi byte chars it will return a wrong char count, but a byte count.
You'll probably need to know this down the track :) For now, get on top of your syntax.

Related

PHP: Use the short if-statement without else?

I'm a fan if the short if-version, example:
($thisVar == $thatVar ? doThis() : doThat());
I'd like to cut out the else-statement though, example:
($thisVar == $thatVar ? doThis());
However, it wont work. Is there any way to do it that I'm missing out?
You can't use it without the else. But you can try this:
($thisVar != $thatVar ?: doThis());
or
if ($thisVar == $thatVar) doThis();
The ternary operator is designed to yield one of two values. It's an expression, not a statement, and you shouldn't use it as a shorter alternative to if/else.
There is no way to leave out the : part: what value would the expression evaluate to if you did?
If you're calling methods with side effects, use if/else. Don't take short cuts. Readability is more important than saving a few characters.
hmm interesting, because executing the below code is valid. Observe:
for ($i = 1; $i <=10; $i++) {
if ($i % 2) {
echo $i;
}
}
The above code indeed, will output 13579
Notice no 'else' clause was used in the above.
If you wanted to inform the user of whether $i % 2 == FALSE ($i's divisor yielded remainder 0), you could include an else clause to print out the even numbers like shown below:
for ($i = 1; $i <=10; $i++) {
if ($i % 2) {
echo "$i is odd";
echo "<br />";
} else {
echo "$i is even";
echo "<br />";
}
}
Giving you the output:
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
I hope my amazingly easy to understand examples will help all newcomers to PHP, hands down the 'best' server-side scripting language for building dynamic web applications :-)
USE NULL TO SKIP STATEMENTS WHEN IT IS IN SHORTHAND
$a == $b? $a = 10 : NULL;
Just use logical operators : AND, OR, &&, ||, etc.
($thisVar === $thatVar) && doThis();
a frequent use is :
$obj = doSomething($params) or throw new \Exception('Failed to do');
Working for me:
$leftHand != $rightHand?doThis():null;
$leftHand == $rightHand?null:doThis();

Using preg_replace() To Increment a Digit in a Phrase [duplicate]

I have a string formed up by numbers and sometimes by letters.
Example AF-1234 or 345ww.
I have to get the numeric part and increment it by one.
how can I do that? maybe with regex?
You can use preg_replace_callback as:
function inc($matches) {
return ++$matches[1];
}
$input = preg_replace_callback("|(\d+)|", "inc", $input);
Basically you match the numeric part of the string using the regex \d+ and replace it with the value returned by the callback function which returns the incremented value.
Ideone link
Alternatively this can be done using preg_replace() with the e modifier as:
$input = preg_replace("|(\d+)|e", "$1+1", $input);
Ideone link
If the string ends with numeric characters it is this simple...
$str = 'AF-1234';
echo $str++; //AF-1235
That works the same way with '345ww' though the result may not be what you expect.
$str = '345ww';
echo $str++; //345wx
#tampe125
This example is probably the best method for your needs if incrementing string that end with numbers.
$str = 'XXX-342';
echo $str++; //XXX-343
Here is an example that worked for me by doing a pre increment on the value
$admNo = HF0001;
$newAdmNo = ++$admNo;
The above code will output HF0002
If you are dealing with strings that have multiple number parts then it's not so easy to solve with regex, since you might have numbers overflowing from one numeric part to another.
For example if you have a number INV00-10-99 which should increment to INV00-11-00.
I ended up with the following:
for ($i = strlen($string) - 1; $i >= 0; $i--) {
if (is_numeric($string[$i])) {
$most_significant_number = $i;
if ($string[$i] < 9) {
$string[$i] = $string[$i] + 1;
break;
}
// The number was a 9, set it to zero and continue.
$string[$i] = 0;
}
}
// If the most significant number was set to a zero it has overflowed so we
// need to prefix it with a '1'.
if ($string[$most_significant_number] === '0') {
$string = substr_replace($string, '1', $most_significant_number, 0);
}
Here's some Python code that does what you ask. Not too great on my PHP, but I'll see if I can convert it for you.
>>> import re
>>> match = re.match(r'(\D*)(\d+)(\D*)', 'AF-1234')
>>> match.group(1) + str(int(match.group(2))+1) + match.group(3)
'AF-1235'
This is similar to the answer above, but contains the code inline and does a full check for the last character.
function replace_title($title) {
$pattern = '/(\d+)(?!.*\d)+/';
return preg_replace_callback($pattern, function($m) { return ++$m[0]; }, $title);
}
echo replace_title('test 123'); // test 124
echo replace_title('test 12 3'); // test 12 4
echo replace_title('test 123 - 2'); // test 123 - 3
echo replace_title('test 123 - 3 - 5'); // test 123 - 3 - 6
echo replace_title('123test'); // 124test

php if-else failing

What is wrong with this if-else statement.
if((strlen($objectData['pss'] >= 8))AND(strlen($objectData['pss'] <= 20)))
{
//do my bidding
}
else
{
echo "String to short or to long";
}
Ultimately I am trying to find if the variable is greater than or equal to 8 chars while being under or equal to 20 chars. My test string is 11 char, and I am seeing string to short/to long. I've done similar to this in the past, so I dunno what I mucked up at the moment (maybe Im just to tired to realize it)
if (strlen($objectData['pss']) >= 8 && strlen($objectData['pss']) <= 20)
if ((strlen($objectData['pss']) >= 8) and (strlen($objectData['pss']) <= 20))
{
//do my bidding
}
else
{
echo "String to short or to long";
}
I have corrected you brackets
Yes you are indeed "to tired".. You are basically counting the length of an expression instead of the string itself:
if((strlen($objectData['pss']) >= 8)AND(strlen($objectData['pss']) <= 20))

php improper comparison behavior

$string = '540';
if (strlen ($string >= 34)){
print_r((substr($string, 0, 30) . "..."));
} else {
print_r(($string));
}
If $string is longer than 34 characters it should be appended with a "...", otherwise it should just print the string.
I think what's happening is that the interpreter is assuming the string is a number when it does the comparison.
It also has the same hiccup if I change $string to
$string = '540 rocks !'
Why is this?
Should be:
if (strlen($string) >= 34)) {
Not
if ($string >= 34)){
If the test you want to do is on the string length, just change this line:
if ($string >= 34)){
into this:
if (strlen($string) >= 34)){

How long is a piece of $string… too long… javascript P2

How can I convert this PHP code to JavaScript?
$string = "string How Long is a Piece of String?";
if (strlen($string) < 5)
{
echo "string is less than 5";
}
else
{
echo "string is more than 5";
}
I assume this is just a really convoluted, badly explained, typo-ridden way of asking how to get the length of a string in JavaScript. If that's the case, just check the length property of the string, like this:
var str = 'How long is a piece of string?';
if (str.length < 5) {
alert('String is less than 5');
} else {
alert('String is greater than or equal to 5');
}
If this is not what you're asking, you really need to clarify the question.

Categories