I'm a total PHP newb, so there is probably a better way of outputting a row's class based on different variables.
Is this bad, and if it is why is it?
if ($variable1 > 0 && $variable2 != 2) {
echo "<tr class='variable1'>";
}
elseif ($variable2==2)
{
echo "<tr class='variable2'>";
}
else {
echo "<tr>";
}
The php code is syntactically correct, although the indentation seems to be messed up. The outputted HTML code is invalid though, since attributes values must be enclosed in double, not single quotes.
I'd also suggest a slight reordering:
if ($variable2 == 2) {
echo '<tr class="variable2">';
} elseif ($variable1 > 0) {
echo '<tr class="variable1">';
} else {
echo '<tr>';
}
You could put the if ($variable2==2) first and then you wouldn't need to negate it on the other if statement. Like this:
if ($variable2==2){
echo '<tr class="variable1">';
}elseif ($variable1 > 0) {
echo '<tr class="variable2">';
}else {
echo '<tr>';
}
Looks okay to me though, but it depends on the rest of the code really, you might be able to change the code slightly to make it easier to read but it looks pretty simple so, if it works, i'd keep it how it is.
I would write it like this:
$class_name = '';
if (2 == $variable2)
{
$class_name = 'variable2';
}
elseif ($variable1 > 0)
{
$class_name = 'variable1';
}
echo '<tr class="' , $class_name , '">';
notice that on the equality test I use the constant before the variable.. this is a habit so that if I miss one equal it would result in an error that I would be forced to correct it instead of a "strange" behavior
another thing is that I give the initial value to $class_name and that will be the default one
also I use apostrophes instead of quotation marks because it is faster (because the way you did it php will parse the string for variables)
and the last thing is that I echo multiple string.. that's also faster than concatenating 3 strings (
echo '<tr class="' , $class_name , '">';
and not echo
'<tr class="' . $class_name . '">';
)
Well you could start with
if ($variable2==2)
which would safe you the $variable2 != 2 if you continue with
elseif ($variable1 > 0)
but generally I see no mistake. Of course this depends on what else you want to do.
2 rules for you to learn how to program:
.1. DRY: Don't Repeat yourself.
if you have your tr tag typed 3 times, you can say for sure that's wrong.
.2. Separate business logic from presentation logic. Use templates for output. Prepare your data first and start output only if everything is ready.
So, first you have to define your variables
if ($variable2 == 2){
$class = "variable1";
}elseif ($variable1 > 0) {
$class = "variable2";
}else {
$class = "";
}
next you have to include a template and write native HTML in it, with as little PHP as possible:
<tr class="<?=$class?>">
Well, that is a really unfortunate approach at many levels, but I can tell you that even I started writing code the way you describe, only that was over 12 years ago.
I can also tell you that eventually mixing php with markup in the same files will come to bite you in the rear, and sooner than you think.
As with most things in life, getting it done faster and worrying about the rest later is a bad approch when developing in PHP.
A few pointers:
Try VERY hard to not mix PHP and HTML or other markup in the same file. Doing this will be more work when first developing but a LOT less work when changing and maintaining your code later.
PHP is an Object-oriented language. Learn how to use that to your advantage. Create libaries of your own classes for later reuse.
Use a good editor/IDE like NetBeans or Komode Editor - which are free.
The best resource for PHP info is the online PHP manual. Not only the manual pages are great, but the code snippets users contribute are full of little gems - and some glaring n00b errors too, but you will learn to filter that.
If you are new to programming in general, PLEASE do yourself a favor and get a book on programming. PHP is a very forgiving language and lets you get away with a lot of bad practices. As I said, those will come back sooner or later to get you.
After you gain some experience consider using a PHP framework, like CodeIgniter, CakePHP or ZendFramework. Try a few of them and choose the one that works for you.
Don't listen to people that tell you that PHP sucks. PHP is the most powerful programming language I have used, maybe excepting C and Prolog. The PHP array is the most powerful data structure I have encountered in any language - except linked lists in C ;-)
You CAN use PHP for every kind of programming task, including Windows and Linux server applications and full desktop graphical applications too. In fact, in my experience, PHP is faster than any dynamic language I have benchmarked it against - python, perl, ruby , tcl are all slower performing than PHP. But don't take my word for it, try it yourself :-)
A couple of links:
30+ PHP best practices for beginners
PHP bad programming practices
PHP OOP in full effect
PHP manual
echo ( ( $variable1 > 0 ) && ( $variable2 != 2 ) )
? "<tr class='variable1'>"
: ( $variable2 == 2 )
? "<tr class='variable2'>"
: "<tr>";
Related
I have three-rows code:
echo '<div>';
for ($i=1; $i<=4; $i++) echo $i;
echo '</div>';
Is there any syntax or function let me rewrite above code in only ONE row, for example:
echo '<div>'.(for...).'</div>'; //error
Thanks
Yes its possible, no you dont want to do it:
echo '<div>' . implode('', array_keys(array_fill(1,4,0))) . '</div>';
While readability is completely personal opinion, there are "common" methods, guidelines, and coding standards which are used by a lot of developers.
And while you don't need to adhere to them, it is always up to you or the company you work for, some of these "ways" are just common sense regardless of your personal choice.
Even if there was a way to do it, why would you want to?
How far do you want to go mixing things together for supposed readability?
echo and a loop are completely different things, and should remain separate.
Answer
In answer to your question, no, it is not possible because PHP needs to differentiate between different "things" - functions, echo statements, variable declaration and usage, etc.
The only things you can "mix" are things which PHP allows to be together, like having a variable in a function parenthesis (function($someVar)).
The only thing you could do (and again this has no point, but your choice) is to put it all on one line, like so:
echo '<div>'; for ($i=1; $i<=4; $i++) { echo $i; } echo '</div>';
But that looks terrible.
I want to quickly see different things - "ah an echo, it prints out XYZ", then I want to see a loop separately so I can see easily what the loop is doing.
This is my first project digging into PHP and mySQL databases, and it's been a steep learning curve so far. I'm near the end of a Wordpress project and could use some help on if...else statements, which have been stumping me for a while. It uses custom fields.
Essentially I need the below flow, where "c01-sp-a" is a one word text variable and "c01-sp-v" is a number. I put variables in [] to clarify:
if ([c01-sp-a] = null)
[text of c01-sp-v]
else
[text of c01-sp-v]
I'd have to repeat this a few times, but I'd imagine having a good example for me would get me going.
Thanks!
You mean like this?
if ($c01_sp_a == null) {
echo $c01_sp_v;
} else {
echo ''.$c01_sp_v'.';
}
your variable can not contain '-' , you have to change your variable names ( i assume that variables are c01_sp_a and $c01_sp_v
if ($c01_sp_a == null)
echo $c01_sp_a;
else
<?php echo $c01_sp_v;?>
Well I want to learn C++ and at the moment I'm only familiar with PHP and Javascript. And I thought a good way to start learning would be to transfer methods in PHP to C++.
So basically I want the code snippets below in C++
The post with the best comments will get a big green tick.
Also, if you know of a good beginners tutorial please leave a comment.
So here are the bits of code I want in C++
First
$array = array('I\'m', 'learning', 'C++');
foreach($array as $word){
echo $word.' ';
}
Second
function foo($num,$ber, $add = true){
if(is_numeric($num) && is_numeric($ber)){
if(!$add){
echo $num*$ber;
}
else{
echo $num + $ber;
}
}
else{
echo 'They aren\'t numbers!';
}
}
foo(2,4, false);
I'm skeptical about the pedagogical usefulness of translating this into C++. Just translating the above code may not be too useful. Take your first example, where you loop over an array of strings and print out each word - sure, I could translate this into C++ using an std::vector<std::string>, iterate over the vector and output each string to stdout. But is that really going to teach you anything? I could also use a C array of const char* pointers, iterate over that and call printf on each one. But is that really going to teach you anything?
Since you already know how to code in PHP and Javascript, you're obviously aware of basic programming concepts like variables, loops, conditionals, etc. But C++ is a dramatically different language than either PHP or Javascript. For one thing, it's statically typed. For another thing, it requires manual memory management. So I think rather than trying to translate PHP code to C++, you'd be better off reading a good introductory book to C++.
never try to learn any complex subject by 'translating' from another one, no matter how well you know the old one.
You'd only get inconsistent concepts, with the limitations of both and the advantages of none.
I think you'd be much better off if you tried to figure it out and asked questions you had about it along the way.
It's been a long running issue that I've come across in many-a-hot-and-steamy coding sessions.
One person codes this way another codes that way. So after much push and pull I'm curious...
Is there any correct way of phrasing a PHP 'IF ELSE' statement?
Personally I use the:
if ($variable == 'setvalue')
{
$variable = executefunctiononvariable($variable);
} else {
$variable = executedifferentfunctiononvariable($variable);
}
After many arguments though I've been presented with other options such as:
if ($variable == 'setvalue')
{
$variable = executefunctiononvariable($variable);
}
else
{
$variable = executedifferentfunctiononvariable($variable);
}
OR
if ($variable == 'setvalue')
$variable = executefunctiononvariable($variable);
else
$variable = executedifferentfunctiononvariable($variable);
OR
if ($variable == 'setvalue') {
$variable = executefunctiononvariable($variable);
} else {
$variable = executedifferentfunctiononvariable($variable);
}
I personally format my if/else like the last one:
if ($variable == 'setvalue') {
$variable = executefunctiononvariable($variable);
} else {
$variable = executedifferentfunctiononvariable($variable);
}
Your version is kind a mixture of 1 and 3, in my mind.
I have also worked with coders that do all of them and have never heard of a standard one.
The php website uses the last one: http://ca2.php.net/manual/en/control-structures.elseif.php
I also use the second example in some cases when the if statement will always be very short. If there's ever a possibiltiy of it getting longer (more than 1 line each) I'll do #1. I try to avoid #2 when possible cause it's hard to add the {} later.
I use the last one:
if ($variable == 'setvalue') {
$variable = executefunctiononvariable($variable);
} else {
$variable = executedifferentfunctiononvariable($variable);
}
That being said, it is pretty unimportant which one you go with, just make sure you are consistent.
The Right Way is to follow your project's coding standard. If you don't have one, adopt one from PHP-FIG, Zend, Symfony, etc.
This form appears very popular:
if (condition) {
statements
} else {
statements
}
For variable assignment I'll use a ternary only if the statement can fit legibly on one line:
$variable = !empty($foo) ? $foo : 'default';
Update: I've removed the bit about a multi-line ternary statements as I no longer consider this a wise practice.
I personnally prefer:
if(something){
doSomething();
}
elseif(somethingElse){
doSomethingElse();
}
else{
doAnotherThing();
}
Don't forget about
if (expression):
// code goes here
elseif (another expression):
// code goes here
else:
// code goes here
endif;
I personally like this structure when I'm cooking some tag soup.
The most important thing is that the programmers working on a project pretty much adhere to the same coding guidelines. So have a meeting and pick one or the other, and then stick with it.
I used to do (2) all the time but got it beaten out of me from Java programming as Sun's coding conventions use (4). So now I'm pretty used to (4). I've been doing a bit of C# lately and it seems to use (2) by default (sigh, here we go again).
In PHP from habit I do (4) but (2) is fine too. I don't like (1) at all.
And (3) is dangerous. Personally I think braces should be required by the syntax of the langauge even if its just for one statement. Saves you getting into trouble. I think that's how Perl does it from memory.
What I also hate is when people do this:
if (something) {
// do something
}
else if (something else) {
}
That one drives me batty. So I only find (2) and (4) acceptable. I don't care which one it is, as long as it's done consistently, preferably within the conventions for the language.
There is no right or wrong way, it is an opinion. Personally, I like the last one best (1TBS???). I never use the one without braces, I consider it bad style in general.
The only people that can really answer this question for you are the other people that are going to work on the code. It is important that everone agrees to a coding standard. Which standard you choose is less important than the fact that everyone uses it.
The PEAR coding standard is the PHP coding standard. I would recommend to get used to it as you will find it in other projects such as Zend, Doctrine, Symfony, Horde and many, many more.
http://framework.zend.com/manual/en/coding-standard.coding-style.html#coding-standard.coding-style.control-statements.if-else-elseif
In short, the is no correct way of doing. As long as it works, whatever you feel is the best, you can use. You should pick one and then stick to it, it will make your code easier to recognise.
The only thing is, if you don't include the "{" character you are limited to one expression or function.
Also, if you are only looking to define variables you can use the following code:
$variable = (CONDITIONAL STATEMENT) ? "It was true" : "It was false";
At my company we use:
if ($variable == 'setvalue')
{
$variable = executefunctiononvariable($variable);
}
else
{
$variable = executedifferentfunctiononvariable($variable);
}
I doesn't really matter aslong as there is a standard
Really to me... it just doesn't matter. I believe you should be able to read either way without issues. Does it really matter if the curly brace is on a new line or not? Does it really matter if there's a space after the closing parenthesis or not?
As long as the code is done in a such way that there's been at least an attempt at making it readable, I really just don't care.
Is there a correct way? Well if there was, then why do we have options of doing it differently?
I am using NetBeans for PHP 6.5.
In my code I frequently use the following type of command:
if (($row = $db->get_row($sql))) {
return $row->folder;
} else {
return FALSE;
}
Netbeans tells me that I should not be using assignments in the IF statement.
Why ?
They are not bad, but they can lead to dangerous mistakes.
In c like languages, where an assignment is an expression, (to support for example a=b=c=1;) a common error is:
if (a = 1) { .. }
But you wanted to have
if (a == 1) { .. }
Some developers have learned to type
if (1 == a) { .. }
To create an error if one '=' is forgotten. But I think that it does not improve the readability.
However modern compilers, give a warning if you write
if (a = 1) { .. }
which I think is a better solution. In that case you are forced to check if it was what you really meant.
It's probably trying to help you avoid the dreaded typo:
if(a = b)
//logic error
Although I would expect an enviroment smart enough to warn you about that, to also be smart enough to have "oh, don't worry about that case" conditions.
Conditionals often include short circuit operators. So, given this example:
if ( a=func(x) && b=func(y) )
{
// do this
}
It may not be immediately obvious, but the second assignment would only occur if the first returned >0, and if func(y) had other side effects that you were expecting, they would not happen either.
In short, if you know what you are doing and understand the side effects, then there is nothing wrong with it. However, you must consider the possibility that someone else may be maintaining your code when you're gone and they might not be as experienced as you.
Also, future maintainers may think you intended the following:
if ( a==func(x) && b==func(y) ) ...
If they "fix" your code, they actually break it.
In languages that allways return a value on assignments it's not bad (I think it's quite common in functional languages), but (as others allready have said while I typed this) it should usually be avoided since you or someone else might mistake it for a comparison. The compiler should usually warn about it, but it can be ignored if you're sure what you're doing...
how would a code look like if you do not assign the $row value in the loop condition
this would be much more complicated i think...
although not that good to read for some maintainers, no?
well you can do it like
$next = mysql_fetch_assoc($result)
do{
...
...
...
$next = mysql_fetch_assoc($result) or break;
}while ($next)
I use them all the time, with loops (not sure why that would make a difference), like:
$counter = 0;
while( $getWhateverDataObj = mysql_fetch_object( $sqlResult )) {
$getWhateverObj->firstName[$counter] = $getWhateverDataObj->firstName;
$getWhateverObj->lastName[$counter] = $getWhateverDataObj->lastName;
$counter++;
}
And it works fine.