How i can use if/else/elseif... in my case,
Because when i try those statment,
It says: syntax error, unexpected 'if' (T_IF)
I need to repeat elseif more than 1x time
$row = array();
$row[] = if($aRow['status'] == "deleted"){'code..'};
This might be what you are after. You would loop over each record in your result array you get from fetchAll(), put your if/elseif block here, then I'm assuming your doing some sort of processing and saving the value to $row array?
$row = array();
$result = $sth->fetchAll();
foreach($result as $aRow){
if($aRow['status'] == "deleted"){
//do something
$row[] = //whatever
}
elseif($aRow['status'] == "something else"){
//do something else;
$row[] = //whatever else
}
}
You have 2 ways for implementing this by PHP:
The 1st way
you can use if/else/elseif:
if ($status_var=="deleted")
{
//code .....
}
elseif ($status_var=="inserted")
{
//code .....
}
elseif ($status_var=="edited")
{
//code .....
}
esle
{
//code .....
}
The 2nd way
You can use switch/case structure:
switch ($status_var)
{
case "deleted":
//code .....
break;
case "inserted":
//code .....
break;
case "edited":
//code .....
break;
default:
//code .....
}
You can use ternary operator to assign the result:
$row = array();
$row[] = $aRow['status'] == "deleted" ? 'code..' : null;
When you need to do more things depending on status, best way would be to introduce a function for that:
function process($aRow) {
if ($aRow['status'] == "deleted") {
// do something when `deleted`
return 1;
} elseif ($aRow['status'] == "new") {
// do something when `new`
return 2;
} elseif ($aRow['status'] == "updated") {
// do something when `updated`
return 3;
} else {
// do something else
return 4;
}
}
$row = array();
$row[] = process($aRow);
Related
How would I write the following foreach with some conditions using array_filter?
foreach ($categories as $category) {
if ($this->request->getParam('category_id')) {
if ($category->getCategoryId() == $this->request->getParam('category_id')) {
$selectedCategory = $category;
break;
}
} else {
No category id in request. Select the first one.
if (array_key_exists(0, $categoryTree) &&
$category->getCategoryId() == $categoryTree[0]['id']
) {
$selectedCategory = $category;
break;
}
}
}
First off, using array_filter isn't helpful in this case as it reduces an array instead of selecting an element. But to show its principles, you could rewrite the code to something like this.
if($this->request->getParam('category_id')){
$filteredCategories = array_filter($categories, function ($category) use ($this){
return $category->getCategoryId() == $this->request->getParam('category_id');
});
if(count($filteredCategories)>0){
return $filteredCategories[0];
}
} else {
[...]
}
I think you want an intersection function and not an array filter.
function key_compare_func($key1, $key2)
{
if ($key1 == $key2->getCategoryId()) {
return 1;
} else {
return 0;
}
}
$selectedCategory = array_intersect_ukey(
$this>request>getParam('category_id'),
$categories,
'key_compare_func'
)
For more information on the different array functions you can look at the PHP manual
Let's say I have a simple code:
while(1) {
myend();
}
function myend() {
echo rand(0,10);
echo "<br>";
if(rand(0,10) < 3) break;
}
This will not work with error code 'Fatal error: Cannot break/continue 1 level on line'.
So is there any possibility to terminate the loop during a subfunctin execution?
Make the loop condition depend upon the return value of the function:
$continue = true;
while( $continue) {
$continue = myend();
}
Then, change your function to be something like:
function myend() {
echo rand(0,10);
echo "<br>";
return (rand(0,10) < 3) ? false : true;
}
There isn't. Not should there be; if your function is called somewhere where you're not in a loop, your code will stop dead. In the example above, your calling code should check the return of the function and then decide whether to stop looping itself. For example:
while(1) {
if (myend())
break;
}
function myend() {
echo rand(0,10);
echo "<br>";
return rand(0,10) < 3;
}
Use:
$cond = true;
while($cond) {
$cond = myend();
}
function myend() {
echo rand(0,10);
echo "<br>";
if(rand(0,10) < 3) return false;
}
I have a method that can return 3 different cases
public function check_verification_status($user_id) {
global $db;
$sql = "SELECT * FROM `users`
WHERE `id` = ".clean($user_id)."
AND `type_id` = 1";
$result = #mysql_query($sql,$db); check_sql(mysql_error(), $sql, 0);
$list = mysql_fetch_array($result);
if ($list['verification_key'] == '' && !$list['verified']) {
//No key or verified
return 0;
} elseif ($list['verification_key'] != '' && !$list['verified']) {
//key exists but not verified = email sent
return 2;
} elseif ($list['verification_key'] != '' && $list['verified']) {
//verified
return 1;
}
}
A form / message is output depending on the return value from this
I would have used bool for return values when comparing 2 cases, what is the proper way of handling more than 2 cases and what would the ideal return value be.
The way i call this:
$v_status = $ver->check_verification_status($user_id);
if ($v_status === 0) {
//do something
} elseif ($v_status === 1) {
//do something else
} elseif ($v_status === 2) {
//do something totally different
}
I want to learn the right way of handling such cases as I run into them often.
note: I know I need to upgrage to mysqli or PDO, its coming soon
What you have is fine, but you can also use a switch statement:
$v_status = $ver->check_verification_status($user_id);
switch ($v_status) {
case 0: {
//do something
break;
}
case 1: {
//do something else
break;
}
case 2: {
//do something totally different
break;
}
}
Not sure if this is even possible, but the basic idea of the code is as follows:
if(isset($_POST['submit'])) {
if($_POST['field'] == 0) {
// do not process the code in the if statement
}
// code to process if the above validation criteria is not met
}
I basically want to try and keep it as simple as possible without lots of if's everywhere, just the quick validation statements at the top, and if none of those if statements are triggered, it will process the code to update the database etc.
I have tried the continue statement function with no joy, I believe that only works with loops.
Thanks!
if(isset($_POST['submit']) && $_POST['field'] != 0) {
}
As a function
function testCondition() {
return isset($_POST['submit']) &&
$_POST['field'] != 0;
}
if (testCondition()) { ... }
You could put all of this in a function and then call 'return' from the inside 'if':
if(isset($_POST['submit']) && validate_form())
{
...
}
function validate_form()
{
if($_POST['field'] == 0) {
return false;
}
if(another check that fails) {
return false;
}
...
return true;
}
To accomplish this as you originally desired, you need to use the break statement. From the PHP manual:
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
if ($val == 'stop') {
break; /* You could also write 'break 1;' here. */
}
echo "$val<br />\n";
}
/* Using the optional argument. */
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5<br />\n";
break 1; /* Exit only the switch. */
case 10:
echo "At 10; quitting<br />\n";
break 2; /* Exit the switch and the while. */
default:
break;
}
}
I'm attempting to optimise the following PHP If/Else statement. Could I rewrite the code to make use to case and switch, or should I leave it as it is, or what?
Code:
if(empty($_GET['id'])){
include('pages/home.php');
}elseif ($_GET['id'] === '13') {
include('pages/servicestatus.php');
}elseif(!empty($_GET['id'])){
$rawdata = fetch_article($db->real_escape_string($_GET['id']));
if(!$rawdata){
$title = "";
$meta['keywords'] = "";
$meta['description'] = "";
}else{
$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>";
}
include("includes/header.php");
echo $pagecontent;
if(!$rawdata){
error_404();
}
}
Thanks
I hate switch statements, but its personal preference to be honest. As far as further optimization i'd suggest taking a look at some form of assembly language. It will give you some general ideas on how to make conditional statements more efficient. That is, it will give you a different out look on things.
if(!empty($_GET['id']))
{
if($_GET['id'] == '13')
{
include('pages/servicestatus.php');
}
else
{
$rawdata = fetch_article($db->real_escape_string($_GET['id']));
if (!$rawdata) {
$title = "";
$meta['keywords'] = "";
$meta['description'] = "";
} else {
$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>";
}
include("includes/header.php");
echo $pagecontent;
if (!$rawdata) {
error_404();
}
}
}
else
{
include('pages/home.php');
}
switch would be appropriate if you had several discrete values for $_GET['id'] that you were checking for.
One suggestion I can make for the sake of readability is that
} elseif (!empty($_GET['id'])) {
only needs to be
} else {
Well i don't think it's necessary to switch to a swith
but you could change
} elseif (!empty($_GET['id'])) {
to just
}else{
You may want to look into breaking up your code into a MVC form; that would make it much easier to maintain your code. At least put the last clause into another file, probably called default.php and include it. Also, you might create an array of id => file key/value sets, lookup the id, and include the file.
if (isset($_GET['id'])) {
$pages = array(
0 => 'home.php',
13 => 'servicestatus.php'
);
if (isset($pages[$_GET['id']])) {
include('pages/' . $pages[$_GET['id']]);
} else {
include('pages/default.php');
}
}
Yes, switch is evaluate once, is efficient than if elseif,
and is easier to maintain with this given structure
switch ($_GET['id'])
{
case 13: ... break;
case 0 : ... break;
default: ... break;
}
I dont know, if you should, or should not, but here I wouldnt. The main reason is, that there is at least one statement, you can omit, and then, you will have just a if-elseif-else-Statement
if (empty($_GET['id'])) { /* code */ }
elseif ($_GET['id'] === '13') { /* code */ }
elseif (!empty($_GET['id'])) { /* code* }
is the same as
if (empty($_GET['id'])) { /* code */ }
elseif ($_GET['id'] === '13') { /* code */ }
else { /* code* }
In the block after that, the statement if(!$rawdata) is also duplicated.