#php if elseif
Explore tagged Tumblr posts
Text
PHP if Operators
Learn how to use PHP if operators with examples, syntax, and real-world use cases. Master conditional logic in PHP easily. ✅ Mastering PHP if Operators: A Complete Guide for Beginners PHP is a powerful server-side scripting language widely used in web development. One of the most essential features of PHP is conditional statements, and at the heart of this lies the if operator. In this guide,…
#php beginner tutorial#php conditional statements#PHP if#php if else#php if elseif#php if statement#php logic
0 notes
Text
How to use bulk bargain in WooCommerce?
You have a (brick and mortar) shop for pretty a while. Your buddies apprehend you, superb you every day and buy from your store. You recognise, as a salesperson, that a glad client is a repeat customer. What do you do? You provide special costs on your great customers, and reductions for big orders. This earns you happy, repeat clients, who will advise you to extra in their buddies and, in the long run, increase your income. Your brand, our expertise — the White Label WordPress development agency that powers your growth.
The specific same good judgment can follow on your e-trade store. You can trap your clients to buy greater, by using creating reductions for bulk orders and reward your unswerving customers.
In this newsletter, we are able to observe various eventualities in which we praise a client with a discount and how to apply them in our WordPress/WooCommerce e-save.
Getting geared up
Before doing any code adjustments, it’s continually an amazing concept to take a full backup of our web page and ensure that we have FTP get admission to or get admission to to cPanel or Plesk or different manipulate panel with get admission to to a document supervisor.
If you surprise what is the first-class way to add code snippets in your website online, have a study our previous article about thoroughly adding PHP code.
We count on that you have already got WordPress with WooCommerce established, and your store is showing at least a few products.
Bulk discount based on total charge
Let’s discover how we are able to apply a bulk cut price when the entire exceeds a positive amount. In the following instance, if the order total is $50, we can offer a reduction of five%. If the order overall is over $a hundred, we are able to provide a reduction of 10%.
If you simplest need to use one tier for cut price, definitely cast off completely the elseif statement.
My cart total right here is $51, so I get a reduction of 5% (=2.55, rounded up to 3):
checkout of order over $50
While here, once I brought some merchandise and were given the total over $one hundred, the discount is extended to 10%:
checkout of order over $one hundred
Exlude certain product classes from cut price
The above code snippet will observe a widespread discount to every fabricated from your keep, so long as the order overall exceeds a predetermined amount. This, however, might not be proper. We can be promoting some products which are already in a reduced fee as a promotion, or we might not want to provide reductions for some luxury gadgets. Build stunning websites for your clients with a reliable White Label WordPress Company by your side.
Let’s first-rate-tune the previous snippet, so as to be able to exclude certain product classes from being eligible for the discounted charge.
In the following instance, my order reaches a complete of $eighty one and I get the 5% cut price.
Checkout no category clear out
However, I want all merchandise in the category “Hoodies” to no longer be eligible for discount. The class ID of “Hoodies”, in my set up, is 23, as I observed touring Products > Categories on my dashboard and clicking on “Hoodies”. So, allow’s amplify the snippet of the previous segment, to exclude all products inside the category with ID 23 from being eligible for bargain:
I added the category ID within the code above in line 6. Now, the identical checkout web page appears quite exclusive:
checkout class clear out
As the hoodie became the product that raised my fee to over $50, the cut price has disappeared. Let’s see the equal cart if I add some more beanies, which can be nevertheless eligible for cut price:
checkout category filter out
Here I do get my bulk cut price of five%, as the entire rate of the beanies exceeds $50.
If you want to exclude more classes, you can genuinely upload a new line after line 6:
Number of gadgets primarily based bulk discount
Here is every other scenario: You are promoting wholesales, your merchandise don’t vary an excessive amount of on prices (or you simplest promote one product) and it makes extra sense to both you and your client to offer a reduction primarily based on quantity of merchandise ordered.
For this, we can use the WooCommerce Bulk Discount, that does exactly this.
Setting up WooCommerce Bulk Discount
Upon installing and activating the plugin, a brand new tab known as Bulk Discount seems on WooCommerce > Settings, that lets in you to create your personal cut price coverage:
wc bulk cut price plugin settings display screen
The maximum important choice right here is the “Discount type”:
Percentage Discount: Much just like the previous use-case we discussed, on an order of more of N items, a percentage bargain may be carried out on the whole charge of the product.
Flat cut price: A constant amount of cash is decreased from the total while you buy more than N objects. For example, if I purchase more than 20 hoodies, I will get a $10 discount, no matter if I purchase 21 or 40 hoodies.
Fixed Discount: An amount of cash is decreased from each object, when you buy extra than N objects. For instance, if the flat cut price is two$ for extra than 10 gadgets, on a product that fees $50. So if I purchase over 10 gadgets, I gets each object on the rate of $8 in line with object.
In each of the above alternatives, you may nevertheless decide ranges, as an instance extraordinary discount for over 10 and over 100 objects.
Examples using WooCommerce Bulk Discount
Let’s see how this works in movement. Here I want to use a flat discount of $15 if a person buys more than 20 of my product Polo”, that prices $20 in step with object. First, we want to choose “Flat cut price” from the dropdown at WooCommerce > Settings > Bulk Discount. Then on the product edit display, we can see a new tab named “Bulk Discount”. The new panel allows you to feature a unique provide text in case you so wish, and then you can add a rule for the bargain, by means of pressing at the button: “Add cut price line”.
Product edit display for bulk cut price
And right here we will see that the flat discount implemented on my order of twenty-two x “Polo”:
checkout display screen with flat bargain
Let’s check this for a fixed bargain of $5 for every object if the order is greater than 20 items. We need to pick “Fixed bargain” from the dropdown at WooCommerce > Settings > Bulk Discount after which input the suitable line at the product edit display screen:
product edit display screen for bulk discount
At the checkout screen after buying, once more, 22 x “Polo”, we will see that now the cut price is 5 greenbacks for each object, that is, I surely sold the 22 polos at $15 every, as opposed to $20 each:
checkout display with fixed cut price
Wrapping up
In this text we explored the diverse methods to praise your customers for bulk orders, by means of offering discounted charges. We noticed the way to:
Offer a reduction whilst the total fee exceeds a particular quantity.
Limit which product classes may be eligible for a complete charge cut price.
Offer a flat, fixed, or by means of percent cut price to clients that purchase greater than a certain amount of objects in line with product.
We wish this article was useful. Please leave a remark when you have used any of those techniques to provide discounted prices to your clients. Let us know when you have any questions.
Also Read : Which one may be nice Blogger or Wordpress in 2025?
What’s the Future of the Jewelry Industry – Online or Offline?
0 notes
Text
Belajar PHP & MySQL
Minggu 1: Pengenalan PHP dan Instalasi Apa itu PHP? Keunggulan dan kegunaannya. Instalasi PHP, web server (XAMPP/Laragon), dan editor teks. Struktur dasar skrip PHP (Tag PHP, komentar). Variabel, tipe data, dan operator dalam PHP. Penggunaan echo dan print untuk output. Pengkondisian (if, else, elseif). Looping (for, while, foreach). Praktik: Buat skrip PHP sederhana (misalnya: kalkulator…
0 notes
Text
Supercharge Your WordPress Development with These 10 PHP Snippets WordPress powers over 40% of the web, making it one of the most popular platforms for developers and bloggers alike. Whether you're customizing themes, building plugins, or tweaking functionality, having a handy set of PHP code snippets can save you hours of work. Here are 10 practical PHP snippets every WordPress developer should keep in their toolkit. 1. Disable WordPress Admin Bar for Non-Admins The admin bar can clutter the frontend for non-admin users. Use this snippet to disable it for everyone except administrators: add_action('after_setup_theme', function() if (!current_user_can('administrator')) show_admin_bar(false); ); This ensures a clean frontend experience for subscribers and other roles. 2. Change Default Login Logo URL Customizing the WordPress login page is a common requirement. Use this snippet to change the logo URL on the login screen: add_filter('login_headerurl', function() return home_url(); // Redirect to your website's homepage ); Combine this with CSS to fully brand the login page for clients or personal projects. 3. Redirect Users After Login Based on Role Direct users to specific pages after login based on their roles: add_filter('login_redirect', function($redirect_to, $request, $user) if (isset($user->roles) && is_array($user->roles)) if (in_array('administrator', $user->roles)) return admin_url(); elseif (in_array('editor', $user->roles)) return home_url('/editor-dashboard'); else return home_url('/welcome'); return $redirect_to; , 10, 3); This snippet improves user navigation and role-specific workflows. 4. Custom Excerpt Length Control the excerpt length in posts to maintain a consistent look across your site: add_filter('excerpt_length', function($length) return 20; // Set the excerpt length to 20 words ); Pair this with a custom read more link for better UX: add_filter('excerpt_more', function() return '... Read More'; ); 5. Remove WordPress Version Number Hiding the WordPress version number improves security by making it harder for attackers to target vulnerabilities: remove_action('wp_head', 'wp_generator'); This simple snippet removes the version meta tag from the HTML source. 6. Add Custom Image Sizes Define and use custom image sizes for different parts of your theme: add_action('after_setup_theme', function() add_image_size('custom-thumb', 400, 300, true); // Cropped image size ); To use this image size in your theme: echo wp_get_attachment_image($attachment_id, 'custom-thumb'); 7. Disable WordPress Auto Updates Sometimes you want to disable automatic updates to maintain more control: add_filter('automatic_updater_disabled', '__return_true'); You can also disable specific updates, such as plugin updates: add_filter('auto_update_plugin', '__return_false'); 8. Custom Maintenance Mode Display a maintenance mode page while working on your site: add_action('template_redirect', function() if (!current_user_can('administrator') && !is_user_logged_in()) wp_die( 'Under MaintenanceWe’ll be back shortly!', 'Maintenance Mode', array('response' => 503) ); ); This ensures only admins can access the site during maintenance. 9. Limit Post Revisions Restrict the number of post revisions saved in the database to optimize performance: define('WP_POST_REVISIONS', 5); // Limit to 5 revisions per post Add this line to your wp-config.php file to apply globally. 10. Custom Dashboard Widget Add a custom widget to the WordPress admin dashboard for quick links or messages: add_action('wp_dashboard_setup', function() wp_add_dashboard_widget( 'custom_dashboard_widget', 'Welcome to Your Dashboard',
function() echo 'Need help? Visit our support center.'; ); ); This snippet is great for client sites where you can provide tailored guidance. Wrapping Up These 10 PHP snippets cover some of the most common tasks WordPress developers encounter. By incorporating these into your workflow, you’ll save time and enhance the functionality of your projects. Bookmark this cheat sheet and customize these snippets to suit your specific needs!
0 notes
Text
Enviar una campaña de MailChimp desde PHP
Enviar una campaña de MailChimp desde PHP aparece primero en nuestro https://jonathanmelgoza.com/blog/enviar-una-campana-de-mailchimp-desde-php/
Veremos un ejemplo sobre cómo enviar una campaña de MailChimp desde PHP para integrarlo en nuestros proyecto web de clientes o propios, te mostraremos código para obtener listas de suscriptores, obtener plantillas predefinidas y varias cosillas más relacionadas con la integración PHP con MailChimp.
Hace poco tuve la necesidad de Integrar MailChimp con PHP.
Afortunadamente MailChimp ofrece una excelente API y una aun mejor documentación por lo que no fue tan complicado conectar ambos.
Ya hemos hablado antes en este blog cómo obtener listas de MailChimp con PHP y ahora seguiremos adelante con este tema.
Lo más importante de este primer post es sin lugar a dudas la función para comunicarse con MailChimp.
Hoy veremos cómo enviar una campaña de MailChimp desde PHP para lo cual haremos varias cosas.
Antes que nada repasaremos la función para conectar a MailChimp para los que no han ido al post anterior.
Posteriormente también repasaremos el código para obtener tus listas de suscriptores en un combo.
Adicional a esto veremos también cómo:
Obtener miembros de una lista
Obtener etiquetas en la que esta un miembro
Obtener plantillas de correo predefinidas por nosotros
Crear una nueva campaña
Enviar una campaña
Antes que nada recuerda que debes de contar con una cuenta en MailChimp y obtener una API KEY para poder vincular.
Conectar con MailChimp desde PHP
function conectar_a_mailchimp( $url, $peticion, $api_key, $data = array() ) if( $peticion == 'GET' ) $url .= '?' . http_build_query($data); $mch = curl_init(); $headers = array( 'Content-Type: application/json', 'Authorization: Basic '.base64_encode( 'user:'. $api_key ) ); curl_setopt($mch, CURLOPT_URL, $url ); curl_setopt($mch, CURLOPT_HTTPHEADER, $headers); curl_setopt($mch, CURLOPT_RETURNTRANSFER, true); curl_setopt($mch, CURLOPT_CUSTOMREQUEST, $peticion); curl_setopt($mch, CURLOPT_TIMEOUT, 200); curl_setopt($mch, CURLOPT_SSL_VERIFYPEER, false); if( $peticion != 'GET' ) curl_setopt($mch, CURLOPT_POST, true); curl_setopt($mch, CURLOPT_POSTFIELDS, json_encode($data) ); return curl_exec($mch);
A partir de aquí toda referencia a la variable $API_KEY hace referencia a la clave del API requerida.
Obtener listas de suscriptores
$data = array( 'fields' => 'lists', 'count' => 5 ); $url = 'https://' . substr($API_KEY,strpos($API_KEY,'-')+1) . '.api.mailchimp.com/3.0/lists/'; $result = json_decode( conectar_a_mailchimp( $url, 'GET', $API_KEY, $data) ); if( !empty($result->lists) ) echo '<select>'; foreach( $result->lists as $list ) echo '<option value="' . $list->id . '">' . $list->name . ' (' . $list->stats->member_count . ')</option>'; echo '</select>'; elseif ( is_int( $result->status ) ) echo '<strong>' . $result->title . ':</strong> ' . $result->detail;
Obtener miembros de una lista
$data = array( 'offset' => '0', 'count' => '2000' ); $url = 'https://' . substr($API_KEY,strpos($API_KEY,'-')+1) . '.api.mailchimp.com/3.0/lists/[IDLISTA]/members/'; $result = json_decode( conectar_a_mailchimp( $url, 'GET', $API_KEY, $data) ); if( !empty($result->members) ) echo '<select>'; foreach( $result->members as $member ) echo '<option value="' . $member->id . '">' . $member->email_address . '</option>'; echo '</select>'; elseif ( is_int( $result->status ) ) echo '<strong>' . $result->title . ':</strong> ' . $result->detail;
Asegúrate de incluir el ID de tu lista, los IDs los obtuvimos con el código anterior.
Obtener etiquetas en la que esta un miembro
$data = array( 'offset' => '0', 'count' => '50' ); $url = 'https://' . substr($API_KEY,strpos($API_KEY,'-')+1) . '.api.mailchimp.com/3.0/lists/[IDLISTA]/members/[IDMIEMBRO]/'; $result = json_decode( conectar_a_mailchimp( $url, 'GET', $API_KEY, $data) ); echo '<select>'; echo '<option value="0">Seleccionar Tag</option>'; if( $result->tags_count > 0 ) for($i=0;$i<$result->tags_count;$i++) echo "<option value='" . $result->tags[$i]->id . "'>" . $result->tags[$i]->name . "</option>"; echo '</select>';
Aquí también debes de cambiar el ID de lista y el ID de miembro, ambos los obtenemos en los combos anteriores.
Obtener plantillas de correo predefinidas por nosotros
$data = array( 'offset' => '0', 'count' => '50', 'type' => 'user' ); $url = 'https://' . substr($API_KEY,strpos($API_KEY,'-')+1) . '.api.mailchimp.com/3.0/templates/'; $result = json_decode( conectar_a_mailchimp( $url, 'GET', $API_KEY, $data) ); echo '<select>'; echo '<option value="0">Seleccionar Template</option>'; if( $result->total_items > 0 ) for($i=0;$i<$result->total_items;$i++) echo "<option value='" . $result->templates[$i]->id . "'>" . $result->templates[$i]->name . "</option>"; echo '</select>';
Aquí obtenemos las plantillas de correo disponibles únicamente creadas por nosotros, para ver todas elimina ‘type’ => ‘user’.
Crear una nueva campaña
$subject = "Asunto"; $reply_to = "[email protected]"; $from_name = "Mi empresa"; $campaign_id = ""; $data = array( "recipients" => array( "list_id" => "[IDLISTA]", "segment_opts" => array( "saved_segment_id" => [IDETIQUETA] )), "type" => "regular", "settings" => array("subject_line" => $subject, "reply_to" => $reply_to, "from_name" => $from_name ) ); $url = "https://" . substr($API_KEY,strpos($API_KEY,"-")+1) . ".api.mailchimp.com/3.0/campaigns/"; $create_campaign = json_decode(conectar_a_mailchimp( $url, "POST", $API_KEY, $data )); $idCampaña = 0; if ( $create_campaign ) if ( ! empty( $create_campaign->id ) && isset( $create_campaign->status ) && "save" == $create_campaign->status ) $idCampaña = $create_campaign->id;
Sustituimos IDLISTA e IDETIQUETA para crear una campaña para una lista de suscriptores pero además para únicamente los que tengan dicho ID de Segmento, eliminar esta linea para enviar a toda la lista.
La campaña se crea como borrador pero aún no se envia.
Enviar una campaña
$data = array(); $url = "https://" . substr($API_KEY,strpos($API_KEY,"-")+1) . ".api.mailchimp.com/3.0/campaigns/".$idCampaña."/actions/send/"; $send_campaign = json_decode(conectar_a_mailchimp( $url, "POST", $API_KEY, $data )); print_r($send_campaign); if ( empty( $send_campaign ) ) echo "Se ha enviado la campaña"; elseif( isset( $send_campaign->detail ) ) $error_detail = $send_campaign->detail;
Con ayuda del IDCAMPAÑA creado en el paso anterior enviamos la campaña.
Como puedes ver enviar una campaña de MailChimp desde PHP no es complicado de hacer.
Puedes consultar más información sobre el API de MailChimp para aprender a hacer más cosas.
Espero y posteriormente seguir agregando más funcionalidades cómo agregar y eliminar suscriptores desde PHP.
Si esta información sobre cómo enviar una campaña de MailChimp desde PHP te fue de utilidad no olvides compartirla en tus redes sociales o dejarnos un comentario en la sección de abajo para aclararte cualquier duda relacionada al tema.
Hasta luego!
2 notes
·
View notes
Text
Php ile Chatgpt yapay zeka sohbet botu sorgulama ve geçmişi hafızaya alarak cevap verme
<?php class ChatApp { private $model; private $messages; public $api_key; public function __construct($model = "gpt-3.5-turbo", $load_file = "") { $this->model = $model; $this->messages = array(); if ($load_file != '') { $this->load($load_file); } } public function chat($message) { if ($message == "exit") { $this->save(); exit(); } elseif ($message == "save") { $this->save(); return…

View On WordPress
0 notes
Video
youtube
PHP - elseif Statements
2 notes
·
View notes
Text
A Php program to execute the switch statement. Using this program we can execute the single data type element for multiple times. The switch-case statement is a substitute for the if-elseif-else statement, which accomplishes the same goal. The switch-case statement compares a variable to a set of values until it finds one that matches, and then executes the code block that corresponds to that match.
https://inlarn.com/php-program-to-execute-the-switch-statement/
0 notes
Text
PHP if...else Statements
Master PHP if, else, and elseif statements with simple examples and best practices. Learn how to use conditions in PHP to control program flow. ✅ PHP if...else Statements – Complete Beginner’s Guide Conditional statements in PHP allow you to make decisions based on conditions. The most basic and commonly used conditional structure is the if...else statement. This tutorial will walk you through…
#learn php conditions#php conditional statements#php control flow#php decision making#php elseif#php if else#php if else syntax#php if examples#php if nested#php if statement#php if tutorial#php logic#ternary operator in php
0 notes
Photo

PHP Conditional Statements: Very often when you write code, you want to perform different actions for different conditions. You can use conditional statements in your code to do this. In PHP we have the following conditional statements: if statement - executes some code if one condition is true if...else statement - executes some code if a condition is true and another code if that condition is false if...elseif...else statement - executes different codes for more than two conditions Ternary Operators In addition to all this conditional statements, PHP provides a shorthand way of writing if…else, called Ternary Operators. The statement uses a question mark (?) and a colon (:) and takes three operands: a condition to check, a result for TRUE and a result for FALSE. #php #code #coding #phpdevelooer #developer #afgprogrammer #codesnippet #phpprogramming https://www.instagram.com/p/CLRhNqpjQyn/?igshid=msos8smu9fd3
0 notes
Text
複数サイト1子テーマ 各サイトごとにブログIDが割り当てられてるので、これをもとに条件分岐させて、インクルードするcssファイルなどを分ける。
header.phpを編集
// 例えばこんな感じ <?php if( $blog_id == 1 ) ://親サイトのスタイルシート ?> <link rel="stylesheet" href="/style.css" type="text/css" /> <?php elseif($blog_id == 2)://サイトID2のスタイルシート ?> <link rel="stylesheet" href="/style1.css" type="text/css" /> <?php elsif://その他のサイトスタイルシート ?> <link rel="stylesheet" href="/style2.css" type="text/css" /> <?php endif; ?>
0 notes
Photo
PHP Control Structures and Loops: if, else, for, foreach, while, and More
Today, we're going to discuss control structures and loops in PHP. I'll show you how to use all the main control structures that are supported in PHP, like if, else, for, foreach, while, and more.
What Is a Control Structure?
In simple terms, a control structure allows you to control the flow of code execution in your application. Generally, a program is executed sequentially, line by line, and a control structure allows you to alter that flow, usually depending on certain conditions.
Control structures are core features of the PHP language that allow your script to respond differently to different inputs or situations. This could allow your script to give different responses based on user input, file contents, or some other data.
The following flowchart explains how a control structure works in PHP.
As you can see in the above diagram, first a condition is checked. If the condition is true, the conditional code will be executed. The important thing to note here is that code execution continues normally after conditional code execution.
Let's consider the following example.
In the above example, the program checks whether or not the user is logged in. Based on the user's login status, they will be redirected to either the Login page or the My Account page. In this case, a control structure ends code execution by redirecting users to a different page. This is a crucial ability of the PHP language.
PHP supports a number of different control structures:
if
else
elseif
switch
while
do-while
for
foreach
and more
Let's take a look at a few of these control structures with examples.
Learning PHP Control Structures
In the previous section, we learned the basics of control structures in PHP and their usefulness in application development. In this section, we'll go through a couple of important control structures that you'll end up using frequently in your day-to-day application development.
PHP If Statement
The if construct allows you to execute a piece of code if the expression provided along with it evaluates to true.
Let's have a look at the following example to understand how it actually works.
<?php $age = 50; if ($age > 30) { echo "Your age is greater than 30!"; } ?>
The above example should output the Your age is greater than 30! message since the expression evaluates to true. In fact, if you want to execute only a single statement, the above example can be rewritten as shown in the following snippet without brackets.
<?php $age = 50; if ($age > 30) echo "Your age is greater than 30!"; ?>
On the other hand, if you have more than one statements to execute, you must use brackets, as shown in the following snippet.
<?php if (is_array($user)) { $user_id = isset($user['user_id']) ? $user['user_id'] : ''; $username = isset($user['username']) ? $user['username'] : ''; // and more statements... } ?>
PHP Else Statement
In the previous section, we discussed the if construct, which allows you to execute a piece of code if the expression evaluates to true. On the other hand, if the expression evaluates to false, it won't do anything. More often than not, you also want to execute a different code snippet if the expression evaluates to false. That's where the else statement comes into the picture.
You always use the else statement in conjunction with an if statement. Basically, you can define it as shown in the following pseudo code.
if (expression) { // code is executed if the expression evaluates to TRUE } else { // code is executed if the expression evaluates to FALSE }
Let's revise the previous example to understand how it works.
<?php $age = 50; if ($age < 30) { echo "Your age is less than 30!"; } else { echo "Your age is greater than or equal 30!"; } ?>
So when you have two choices, and one of them must be executed, you can use the if-else construct.
PHP Else If Statement
We can consider the elseif statement as an extension to the if-else construct. If you've got more than two choices to choose from, you can use the elseif statement.
Let's study the basic structure of the elseif statement, as shown in the following pseudo code.
if (expression1) { // code is executed if the expression1 evaluates to TRUE } elseif (expression2) { // code is executed if the expression2 evaluates to TRUE } elseif (expression3) { // code is executed if the expression3 evaluates to TRUE } else { // code is executed if the expression1, expression2 and expression3 evaluates to FALSE, a default choice }
Again, let's try to understand it using a real-world example.
<?php $age = 50; if ($age < 30) { echo "Your age is less than 30!"; } elseif ($age > 30 && $age < 40) { echo "Your age is between 30 and 40!"; } elseif ($age > 40 && $age < 50) { echo "Your age is between 40 and 50!"; } else { echo "Your age is greater than 50!"; } ?>
As you can see in the above example, we have multiple conditions, so we've used a series of elseif statements. In the event that all if conditions evaluate to false, it executes the code provided in the last else statement.
PHP Switch Statement
The switch statement is somewhat similar to the elseif statement which we've just discussed in the previous section. The only difference is the expression which is being checked.
In the case of the elseif statement, you have a set of different conditions, and an appropriate action will be executed based on a condition. On the other hand, if you want to compare a variable with different values, you can use the switch statement.
As usual, an example is the best way to understand the switch statement.
<?php $favourite_site = 'Code'; switch ($favourite_site) { case 'Business': echo "My favourite site is business.tutsplus.com!"; break; case 'Code': echo "My favourite site is code.tutsplus.com!"; break; case 'Web Design': echo "My favourite site is webdesign.tutsplus.com!"; break; case 'Music': echo "My favourite site is music.tutsplus.com!"; break; case 'Photography': echo "My favourite site is photography.tutsplus.com!"; break; default: echo "I like everything at tutsplus.com!"; } ?>
As you can see in the above example, we want to check the value of the $favourite_site variable, and based on the value of the $favourite_site variable we want to print a message.
For each value you want to check with the $favourite_site variable, you have to define the case block. If the value is matched with a case, the code associated with that case block will be executed. After that, you need to use the break statement to end code execution. If you don't use the break statement, script execution will be continued up to the last block in the switch statement.
Finally, if you want to execute a piece of code if the variable's value doesn't match any case, you can define it under the default block. Of course, it's not mandatory—it's just a way to provide a default case.
So that's the story of conditional control structures. We'll discuss loops in PHP in the next section.
Loops in PHP
Loops in PHP are useful when you want to execute a piece of code repeatedly until a condition evaluates to false. So code is executed repeatedly as long as a condition evaluates to true, and as soon as the condition evaluates to false, the script continues executing the code after the loop.
The following flowchart explains how loops work in PHP.
As you can see in the above screenshot, a loop contains a condition. If the condition evaluates to true, the conditional code is executed. After execution of the conditional code, control goes back to the loop condition, and the flow continues until the condition evaluates to false.
In this section, we'll go through the different types of loops supported in PHP.
While Loop in PHP
The while loop is used when you want to execute a piece of code repeatedly until the while condition evaluates to false.
You can define it as shown in the following pseudo code.
while (expression) { // code to execute as long as expression evaluates to TRUE }
Let's have a look at a real-world example to understand how the while loop works in PHP.
<?php $max = 0; echo $i = 0; echo ","; echo $j = 1; echo ","; $result=0; while ($max < 10 ) { $result = $i + $j; $i = $j; $j = $result; $max = $max + 1; echo $result; echo ","; } ?>
If you're familiar with the Fibonacci series, you might recognize what the above program does—it outputs the Fibonacci series for the first ten numbers. The while loop is generally used when you don't know the number of iterations that are going to take place in a loop.
Do-While Loop in PHP
The do-while loop is very similar to the while loop, with the only difference being that the while condition is checked at the end of the first iteration. Thus, we can guarantee that the loop code is executed at least once, irrespective of the result of the while expression.
Let's have a look at the syntax of the do-while loop.
do { // code to execute } while (expression);
Let's go through a real-world to understand possible use-cases where you can use the do-while loop.
<?php $handle = fopen("file.txt", "r"); if ($handle) { do { $line = fgets($handle); // process the line content } while($line !== false); } fclose($handle); ?>
In the above example, we're trying to read a file line by line. Firstly, we've opened a file for reading. In our case, we're not sure if the file contains any content at all. Thus, we need to execute the fgets function at least once to check if a file contains any content. So we can use the do-while loop here. do-while evaluates the condition after the first iteration of the loop.
For Loop in PHP
Generally, the for loop is used to execute a piece of code for a specific number of times. In other words, if you already know the number of times you want to execute a block of code, it's the for loop which is the best choice.
Let's have a look at the syntax of the for loop.
for (expr1; expr2; expr3) { // code to execute }
The expr1 expression is used to initialize variables, and it's always executed. The expr2 expression is also executed in the beginning of a loop, and if it evaluates to true, the loop code is executed. After execution of the loop code, the expr3 is executed. Generally, the expr3 is used to alter the value of a variable which is used in the expr2 expression.
Let's go through the following example to see how it works.
<?php for ($i=1; $i<=10; ++$i) { echo sprintf("The square of %d is %d.</br>", $i, $i*$i); } ?>
The above program outputs the square of the first ten numbers. It initializes $i to 1, repeats as long as $i is less than or equal to 10, and adds 1 to $i at each iteration.
For Each in PHP
The foreach loop is used to iterate over array variables. If you have an array variable, and you want to go through each element of that array, the foreach loop is the best choice.
Let's have a look at a couple of examples.
<?php $fruits = array('apple', 'banana', 'orange', 'grapes'); foreach ($fruits as $fruit) { echo $fruit; echo "<br/>"; } $employee = array('name' => 'John Smith', 'age' => 30, 'profession' => 'Software Engineer'); foreach ($employee as $key => $value) { echo sprintf("%s: %s</br>", $key, $value); echo "<br/>"; } ?>
If you want to access array values, you can use the first version of the foreach loop as shown in the above example. On the other hand, if you want to access both a key and a value, you can do it as shown in the $employee example above.
Breaking Out of the Loop
There are times when you might want to break out of a loop before it runs it course. This can be achieved easily using the break keyword. It will get you out of the current for, foreach, while, do-while or switch structure.
You can also use break to get out of multiple nested loops by supplying a numeric argument. For example, using break 3 will break you out of 3 nested loops. However, you cannot pass a variable as the numeric argument if you are using a PHP version greater than or equal to 5.4.
<?php echo 'Simple Break'; for($i = 1; $i <= 2; $i++) { echo "\n".'$i = '.$i.' '; for($j = 1; $j <= 5; $j++) { if($j == 2) { break; } echo '$j = '.$j.' '; } } /* Simple Break i = 1 j = 1 i = 2 j = 1 */ echo 'Multi-level Break'; for($i = 1; $i <= 2; $i++) { echo "\n".'$i = '.$i.' '; for($j = 1; $j <= 5; $j++) { if($j == 2) { break 2; } echo '$j = '.$j.' '; } } /* Multi-level Break i = 1 j = 1 */ ?>
Another keyword that can interrupt loops in PHP is continue. However this only skips the rest of the current loop iteration instead of breaking out of the loop altogether. Just like break, you can also use a numerical value with continue to specify how many nested loops should it skip for current iteration.
<?php echo 'Simple Continue'; for($i = 1; $i <= 2; $i++) { echo "\n".'$i = '.$i.' '; for($j = 1; $j <= 5; $j++) { if($j == 2) { continue; } echo '$j = '.$j.' '; } } /* Simple Continue i = 1 j = 1 j = 3 j = 4 j = 5 i = 2 j = 1 j = 3 j = 4 j = 5 */ echo 'Multi-level Continue'; for($i = 1; $i <= 2; $i++) { echo "\n".'$i = '.$i.' '; for($j = 1; $j <= 5; $j++) { if($j == 2) { continue 2; } echo '$j = '.$j.' '; } } /* Multi-level Continue i = 1 j = 1 i = 2 j = 1 */ ?>
Conclusion
In this article, we discussed different control structures and loops in PHP. They are an essential part of PHP—or any programming language for that matter.
Learn PHP With a Free Online Course
If you want to learn PHP, check out our free online course on PHP fundamentals!
In this course, you'll learn the fundamentals of PHP programming. You'll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you'll build up to coding classes for simple object-oriented programming (OOP). Along the way, you'll learn all the most important skills for writing apps for the web: you'll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.
FREE
PHP
PHP Fundamentals
Jeremy McPeak
by Sajal Soni via Envato Tuts+ Code https://ift.tt/31EUx8s
0 notes
Photo

PHP 7.x — P26: elseif Statement ☞ https://bit.ly/2P47NwA #php #laravel
0 notes
Photo

PHP 7.x — P26: elseif Statement ☞ https://bit.ly/2P47NwA #php #laravel
0 notes
Photo

PHP 7.x — P26: elseif Statement ☞ https://bit.ly/2P47NwA #php #laravel
0 notes
Text
A Php program to execute the switch statement. Using this program we can execute the single data type element for multiple times. The switch-case statement is a substitute for the if-elseif-else statement, which accomplishes the same goal. The switch-case statement compares a variable to a set of values until it finds one that matches, and then executes the code block that corresponds to that match.
https://inlarn.com/php-program-to-execute-the-switch-statement/
0 notes