How to import a product programmatically in magento 2

Solution for : How to import a product programmatically in Magento 2

Below is the simple example fo achieve the solution:

use Magento\Framework\App\Bootstrap;

include("../app/bootstrap.php");
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$simpleProduct = $objectManager->create('\Magento\Catalog\Model\Product');
$simpleProduct->setSku('Testing3');
$simpleProduct->setName('Testing3');
$simpleProduct->setAttributeSetId(9);
$simpleProduct->setCategoryIds(3);
$simpleProduct->setDescription('This is for testing');
$simpleProduct->setStatus(1);
$simpleProduct->setTypeId('simple');
$simpleProduct->setPrice(500);
$simpleProduct->setWebsiteIds(array(1));
$simpleProduct->setVisibility(4);
$simpleProduct->setUrlKey('Testing3');

$simpleProduct->setStockData(array(
    'is_in_stock' => 1, //Stock Availability
    'qty' => 100//qty
        )
);

$attr = $simpleProduct->getResource()->getAttribute('color');
$attributeOptionId = $attr->getSource()->getOptionId('Red'); //name in Default Store View
$simpleProduct->setData('color', $attributeOptionId);

$simpleProduct->save();
$simpleProductId = $simpleProduct->getId();
echo "Simple Product ID: " . $simpleProductId . "\n";

How to calculate minute difference between two date-times in PHP?

Solution for : How to calculate minute difference between two date-times in PHP?

Below is the simple example fo achieve the solution:

$to_time = strtotime("2008-12-13 10:42:00");
$from_time = strtotime("2008-12-13 10:21:00");
echo round(abs($to_time - $from_time) / 60,2). " minute";

How to read if a checkbox is checked in PHP?

Solution for :How to read if a checkbox is checked in PHP?

If our HTML page looks like this:


After submitting the form we can check it with:

isset($_POST['checkbox1'])

OR

if ($_POST['checkbox1'] == 'value1'){ 

//I am checked.

}

Test if number is odd or even in php

Solution for : What is the simplest most basic way to find out if a number/variable is odd or even in PHP? Is it something to do with mod?

You were right in thinking mod was a good place to start. Here is an expression which will return true if $number is even, false if odd:

$number % 2 == 0

Example:

$number = 20;
if ($number % 2 == 0) {
  print "I am even";
}

Output:

I am even

How to find and replace text in a MySQL database

Solution for : How to find and replace text in a MySQL database

I have a column containing urls (id, url):

http://www.example.com/articles/updates/123
http://www.example.com/articles/updates/345
http://www.example.com/articles/updates/234

I'd like to change the word "updates" to "events". Is it possible to do this with a script?

QUERY: We can achieve the above requirements using below query.

UPDATE your_table
SET your_field = REPLACE(your_field, 'articles/updates/', 'articles/events/')
WHERE your_field LIKE '%articles/updates/%'

Find duplicate records in MySQL

Solution for :I want to pull out duplicate records in a MySQL Database.

The key is to rewrite this query so that it can be used as a sub-query.

EXAMPLE QUERY:

SELECT firstname, 
   lastname, 
   list.address 
FROM list
   INNER JOIN (SELECT address
               FROM   list
               GROUP  BY address
               HAVING COUNT(id) > 1) dup
           ON list.address = dup.address;

How to find all the tables in MySQL with specific column names in them?

Solution for :How to find all the tables in MySQL with specific column names in them?

To get all tables with columns columnA or ColumnB in the database YourDatabase:

QUERY:

SELECT DISTINCT TABLE_NAME 
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME IN ('columnA','ColumnB')
        AND TABLE_SCHEMA='YourDatabase';

Insert into a MySQL table or update if exists

Solution for :Insert into a MySQL table or update if exists

If I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.

For example:

insert into table (id, name, age) values(1, "A", 20)

Let’s say the unique key is id, and in my database there is a row with id = 1. In that case I want to update that row with these values. Normally this gives an error. If I use insert IGNORE it will ignore the error, but it still won’t update.

We can use INSERT ... ON DUPLICATE KEY UPDATE

QUERY:

INSERT INTO table (id, name, age) VALUES(1, "A", 20) ON DUPLICATE KEY UPDATE    
name="A", age=20

How to output MySQL query results in CSV format?

Solution for :Is there an easy way to run a MySQL query from the Linux command line and output the results in CSV format?

SELECT order_id,product_name,qty
FROM orders
WHERE foo = 'bar'
INTO OUTFILE '/var/lib/mysql-files/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';

Using this command columns names will not be exported.

Also note that /var/lib/mysql-files/orders.csv will be on the server that is running MySQL. The user that the MySQL process is running under must have permissions to write to the directory chosen, or the command will fail.

If you want to write output to your local machine from a remote server (especially a hosted or virtualize machine such as Heroku or Amazon RDS), this solution is not suitable.

jQuery Ajax POST example with PHP

Solution for : jQuery Ajax POST example with PHP

I would like to share a detailed way of how to post with PHP + Ajax along with errors thrown back on failure.

First of all, create two files, for example form.php and process.php.

We will first create a form which will be then submitted using the jQuery .ajax() method. The rest will be explained in the comments.

form.php

Validate the form using jQuery client-side validation and pass the data to process.php.

$(document).ready(function() {
    $('form').submit(function(event) { //Trigger on form submit
        $('#name + .throw_error').empty(); //Clear the messages first
        $('#success').empty();

        //Validate fields if required using jQuery

        var postForm = { //Fetch form data
            'name'     : $('input[name=name]').val() //Store name fields value
        };

        $.ajax({ //Process the form using $.ajax()
            type      : 'POST', //Method type
            url       : 'process.php', //Your form processing file URL
            data      : postForm, //Forms name
            dataType  : 'json',
            success   : function(data) {
                            if (!data.success) { //If fails
                                if (data.errors.name) { //Returned if any error from process.php
                                    $('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
                                }
                            }
                            else {
                                    $('#success').fadeIn(1000).append('

' + data.posted + '

'); //If successful, than throw a success message } } }); event.preventDefault(); //Prevent the default submit }); });

Now we will take a look at process.php

$errors = array(); //To store errors
$form_data = array(); //Pass back the data to `form.php`

/* Validate the form on the server side */
if (empty($_POST['name'])) { //Name cannot be empty
    $errors['name'] = 'Name cannot be blank';
}

if (!empty($errors)) { //If errors in validation
    $form_data['success'] = false;
    $form_data['errors']  = $errors;
}
else { //If not, process the form, and return true on success
    $form_data['success'] = true;
    $form_data['posted'] = 'Data Was Posted Successfully';
}

//Return the data back to form.php
echo json_encode($form_data);

How to calculate the difference between two dates using PHP?

Solution for : How to calculate the difference between two dates using PHP?

I suggest to use DateTime and DateInterval objects.

$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days "; 

// shows the total amount of days (not divided into years, months and days like above)
echo "difference " . $interval->days . " days ";

read more php DateTime::diff manual

From the manual:

As of PHP 5.2.2, DateTime objects can be compared using comparison operators.

$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2); // bool(false)
var_dump($date1 < $date2);  // bool(true)
var_dump($date1 > $date2);  // bool(false)

Returning JSON from a PHP Script: A Quick Guide

JSON (JavaScript Object Notation) has become the standard format for exchanging data between clients and servers. If you're working with PHP, returning JSON from your script is straightforward and incredibly useful for building APIs or handling AJAX requests.

Why Use JSON?

  • Lightweight and easy to read
  • Natively supported by JavaScript
  • Ideal for client-server communication

How to Return JSON in PHP

Here’s a step-by-step guide:

1. Set the Content-Type Header

To ensure the response is treated as JSON, use:

header('Content-Type: application/json');

2. Create Your Data

Build an associative array or object to hold your data:

$data = [
    "status" => "success",
    "message" => "Data retrieved successfully",
    "data" => [1, 2, 3, 4]
];

3. Convert to JSON

Use json_encode() to convert your PHP data into a JSON string:

echo json_encode($data);

Example Script

Here’s a complete example:

 "success",
    "message" => "This is your JSON response!",
    "items" => ["item1", "item2", "item3"]
];

// Return JSON
echo json_encode($data);
?>

Error Handling

Always check for encoding errors:

 "JSON encoding failed"]);
}

?>

Testing Your Script

  • Use tools like Postman to test your script.
  • For a quick check, call your PHP script via AJAX or in the browser.

With this guide, you can start building JSON-based APIs and create seamless client-server integrations. For more tips, check out See Coding Blog!!

Getting product Image url in Magento 2

Solution for : Getting product Image url in Magento 2.

We can get using below simple lines:

 
$imagehelper = $objectManager->create('Magento\Catalog\Helper\Image');
$image = $imagehelper->init($_product,'category_page_list')->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize(400)->getUrl();

echo '';

Some useful MySQL DATABASE interview questions

How do you start MySQL on Linux?
- /etc/init.d/mysql start

How do you start and stop MySQL on Windows?
net start MySQL, net stop MySQL
What’s the default port for MySQL Server?
3306
 
What does tee command do in MySQL?
 tee followed by a filename turns on MySQL logging to a specified file. It can be stopped by command notee.
 
Can you save your connection settings to a conf file?
Yes, and name it ~/.my.conf. You might want to change the permissions on the file to 600, so that it’s not readable by others.
 
Have you ever used MySQL Administrator and MySQL Query Browser? Describe the tasks you accomplished with these tools.
 
What are some good ideas regarding user security in MySQL?
There is no user without a password. There is no user without a user name. There is no user whose Host column contains % (which here indicates that the user can log in from anywhere in the network or the Internet). There are as few users as possible (in the ideal case only root) who have unrestricted access.
 
How do you change a password for an existing user via mysqladmin?
mysqladmin -u root -p password "newpassword"
 
Explain the difference between MyISAM Static and MyISAM Dynamic.
In MyISAM static all the fields have fixed width. The Dynamic MyISAM table would include fields such as TEXT, BLOB, etc. to accommodate the data types with various lengths. MyISAM Static would be easier to restore in case of corruption, since even though you might lose some data, you know exactly where to look for the beginning of the next record.
 
What does myisamchk do?
It compressed the MyISAM tables, which reduces their disk usage.
 
Explain advantages of InnoDB over MyISAM?
Row-level locking, transactions, foreign key constraints and crash recovery.
 
Explain advantages of MyISAM over InnoDB?
Much more conservative approach to disk space management - each MyISAM table is stored in a separate file, which could be compressed then with myisamchk if needed. With InnoDB the tables are stored in tablespace, and not much further optimization is possible. All data except for TEXT and BLOB can occupy 8,000 bytes at most. No full text indexing is available for InnoDB. TRhe COUNT(*)s execute slower than in MyISAM due to tablespace complexity.
 
What are HEAP tables in MySQL?
HEAP tables are in-memory. They are usually used for high-speed temporary storage. No TEXT or BLOB fields are allowed within HEAP tables. You can only use the comparison operators = and <=>. HEAP tables do not support AUTO_INCREMENT. Indexes must be NOT NULL.
 
How do you control the max size of a HEAP table?
MySQL config variable max_heap_table_size.
 
Explain the difference between mysql and mysqli interfaces in PHP?
mysqli is the object-oriented version of mysql library functions.
 
What are CSV tables?
Those are the special tables, data for which is saved into comma-separated values files. They cannot be indexed.
 
Explain federated tables. - Introduced in MySQL 5.0, federated tables allow access to the tables located on other databases on other servers.
 
What is SERIAL data type in MySQL?
BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT
 
What happens when the column is set to AUTO INCREMENT and you reach the maximum value for that table?
It stops incrementing. It does not overflow to 0 to prevent data losses, but further inserts are going to produce an error, since the key has been used already.
 
Explain the difference between FLOAT, DOUBLE and REAL.
FLOATs store floating point numbers with 8 place accuracy and take up 4 bytes. DOUBLEs store floating point numbers with 16 place accuracy and take up 8 bytes. REAL is a synonym of FLOAT for now.
 
If you specify the data type as DECIMAL (5,2), what’s the range of values that can go in this table? - 999.99 to -99.99. Note that with the negative number the minus sign is considered one of the digits.
 
Use mysqldump to create a copy of the database?
 mysqldump -h mysqlhost -u username -p mydatabasename > dbdump.sql
 
What happens if a table has one column defined as TIMESTAMP? 
That field gets the current timestamp whenever the row gets altered.
 
But what if you really want to store the timestamp data, such as the publication date of the article? Create two columns of type TIMESTAMP and use the second one for your real data.
 
Explain the difference between BOOL, TINYINT and BIT.
Prior to MySQL 5.0.3: those are all synonyms. After MySQL 5.0.3: BIT data type can store 8 bytes of data and should be used for binary data.
 

PHP interview Questions ( basics )

  1. What is PHP?
    PHP is a server side scripting language commonly used for web applications. PHP has many frameworks and cms for creating websites.Even a non technical person can cretae sites using its CMS.WordPress,osCommerce are the famus CMS of php.It is also an object oriented programming language like java,C-sharp etc.It is very eazy for learning

  2. What is the use of "echo" in php?
    It is used to print a data in the webpage, Example:
     echo 'Car insurance';  
    The following code print the text in the webpage

  3. How to include a file to a php page?
    We can include a file using include() " or "require()" function with file path as its parameter.

  4. What's the difference between include and require?
    If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.

  5. require_once(), require(), include(). What is difference between them?
    require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the "function re-declared" error.

  6. Differences between GET and POST methods ?
    We can send 1024 bytes using GET method but POST method can transfer large amount of data and POST is the secure method than GET method .

  7. How to declare an array in php?
    Eg :
     var $arr = array('apple', 'grape', 'lemon');

  8. What is the use of 'print' in php?
    This is not actually a real function, It is a language construct. So you can use with out parentheses with its argument list.

    Example
    print('PHP Interview questions');
     print 'Job Interview ');

  9. What is use of in_array() function in php ?
    in_array used to checks if a value exists in an array

  10. What is use of count() function in php ?
    count() is used to count all elements in an array, or something in an object

  11. What’s the difference between include and require?
    It’s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.

  12. What is the difference between Session and Cookie?
    The main difference between sessions and cookies is that sessions are stored on the server, and cookies are stored on the user’s computers in the text file format. Cookies can not hold multiple variables,But Session can hold multiple variables.We can set expiry for a cookie,The session only remains active as long as the browser is open.Users do not have access to the data you stored in Session,Since it is stored in the server.Session is mainly used for login/logout purpose while cookies using for user activity tracking

  13. How to set cookies in PHP?
    Setcookie("sample", "ram", time()+3600);

  14. How to Retrieve a Cookie Value?
    eg :
    echo $_COOKIE["user"];

  15. How to create a session? How to set a value in session ? How to Remove data from a session?
    Create session :
     session_start();
    Set value into session :
    $_SESSION['USER_ID']=1;
    Remove data from a session :
    unset($_SESSION['USER_ID'];

  16. what types of loops exist in php?
    for,while,do while and foreach (NB: You should learn its usage)

  17. How to create a mysql connection?
    mysql_connect(servername,username,password);

  18. How to select a database?
    mysql_select_db($db_name);

  19. How to execute an sql query? How to fetch its result ?
    $my_qry = mysql_query("SELECT * FROM `users` WHERE `u_id`='1'; "); 
    $result = mysql_fetch_array($my_qry);
    echo $result['First_name'];
    
  20. Write a program using while loop
    $my_qry = mysql_query("SELECT * FROM `users` WHERE `u_id`='1'; "); 
    while($result = mysql_fetch_array($my_qry))
    {
    echo $result['First_name'.]."<br/>";
    }
    
  21. How we can retrieve the data in the result set of MySQL using PHP?
    • 1. mysql_fetch_row
    • 2. mysql_fetch_array
    • 3. mysql_fetch_object
    • 4. mysql_fetch_assoc 
  22. What is the use of explode() function ?
    Syntax : array explode ( string $delimiter , string $string [, int $limit ] );
    This function breaks a string into an array. Each of the array elements is a substring of string formed by splitting it on boundaries formed by the string delimiter.

  23. What is the difference between explode() and split() functions?
    Split function splits string into array by regular expression. Explode splits a string into array by string.

  24. What is the use of mysql_real_escape_string() function?
    It is used to escapes special characters in a string for use in an SQL statement

  25. Write down the code for save an uploaded file in php.
    f ($_FILES["file"]["error"] == 0)
    {
    move_uploaded_file($_FILES["file"]["tmp_name"],
          "upload/" . $_FILES["file"]["name"]);
          echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
    }
    
  26. How to create a text file in php?
    $filename = "/home/user/guest/newfile.txt";
    $file = fopen( $filename, "w" );
    if( $file == false )
    {
    echo ( "Error in opening new file" ); exit();
    }
    fwrite( $file, "This is a simple test\n" );
    fclose( $file );
    
  27. How to strip whitespace (or other characters) from the beginning and end of a string ?
    The trim() function removes whitespaces or other predefined characters from both sides of a string.

  28. What is the use of header() function in php ?
    The header() function sends a raw HTTP header to a client browser.Remember that this function must be called before sending the actual out put.For example, You do not print any HTML element before using this function.

  29. How to redirect a page in php?
    The following code can be used for it,
    header("Location:index.php");

     
  30. How stop the execution of a php scrip ?
    exit() function is used to stop the execution of a page

  31. How to set a page as a home page in a php based site ?
    index.php is the default name of the home page in php based sites

  32. How to find the length of a string?
    strlen() function used to find the length of a string

  33. what is the use of rand() in php?
    It is used to generate random numbers.If called without the arguments it returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 6 and 12 (inclusive), for example, use rand(6, 12).This function does not generate cryptographically safe values, and should not be used for cryptographic uses. If you want a cryptographically secure value, consider using openssl_random_pseudo_bytes() instead.

  34. what is the use of isset() in php?
    This function is used to determine if a variable is set and is not NULL

  35. What is the difference between mysql_fetch_array() and mysql_fetch_assoc() ?
    mysql_fetch_assoc function Fetch a result row as an associative array, While mysql_fetch_array() fetches an associative array, a numeric array, or both

  36. What is mean by an associative array?
    Associative arrays are arrays that use string keys is called associative arrays.

  37. What is the importance of "method" attribute in a html form?
    "method" attribute determines how to send the form-data into the server.There are two methods, get and post. The default method is get.This sends the form information by appending it on the URL.Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

  38. What is the importance of "action" attribute in a html form?
    The action attribute determines where to send the form-data in the form submission.

  39. What is the use of "enctype" attribute in a html form?
    The enctype attribute determines how the form-data should be encoded when submitting it to the server. We need to set enctype as "multipart/form-data" when we are using a form for uploading files

  40. How to create an array of a group of items inside an HTML form ?
    We can create input fields with same name for "name" attribute with squire bracket at the end of the name of the name attribute, It passes data as an array to PHP.
    For instance :
     
    
     
    
    
    
  41. Define Object-Oriented Methodology
    Object orientation is a software/Web development methodology that is based on the modeling a real world system.An object is the core concept involved in the object orientation. An object is the copy of the real world enity.An object oriented model is a collection of objects and its inter-relationships

  42. How do you define a constant?
    Using define() directive, like
     define ("MYCONSTANT",150)

  43. How send email using php?
    To send email using PHP, you use the mail() function.This mail() function accepts 5 parameters as follows (the last 2 are optional). You need webserver, you can't send email from localhost. eg :
     mail($to,$subject,$message,$headers); 
  44. How to find current date and time?
    The date() function provides you with a means of retrieving the current date and time, applying the format integer parameters indicated in your script to the timestamp provided or the current local time if no timestamp is given. In simplified terms, passing a time parameter is optional - if you don't, the current timestamp will be used.

  45. Difference between mysql_connect and mysql_pconnect?
    There is a good page in the php manual on the subject, in short mysql_pconnect() makes a persistent connection to the database which means a SQL link that do not close when the execution of your script ends. mysql_connect()provides only for the databasenewconnection while using mysql_pconnect , the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection... the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use.

  46. What is the use of "ksort" in php?
    It is used for sort an array by key in reverse order.

  47. What is the difference between $var and $$var?
    They are both variables. But $var is a variable with a fixed name. $$var is a variable who's name is stored in $var. For example, if $var contains "message", $$var is the same as $message.

  48. What are the encryption techniques in PHP
    MD5 PHP implements the MD5 hash algorithm using the md5 function,
    eg : $encrypted_text = md5 ($msg);
    mcrypt_encrypt :-
     string mcrypt_encrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] ); 
    Encrypts plaintext with given parameters

  49. What is the use of the function htmlentities?
    htmlentities Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

  50. How to delete a file from the system
    Unlink() deletes the given file from the file system.

  51. How to get the value of current session id?
    session_id() function returns the session id for the current session.

  52. What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?
    • Mysql_fetch_array Fetch a result row as an associative array, a numeric array, or both.
    • mysql_fetch_object ( resource result ) Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows
    • mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
    •  
  53. What are the different types of errors in PHP ?
    Here are three basic types of runtime errors in PHP:
    • 1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script - for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all - although you can change this default behavior.
    • 2. Warnings: These are more serious errors - for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.
    • 3. Fatal errors: These are critical errors - for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP's default behavior is to display them to the user when they take place.
  54. what is sql injection ?
    SQL injection is a malicious code injection technique.It exploiting SQL vulnerabilities in Web applications

  55. What is x+ mode in fopen() used for?
    Read/Write. Creates a new file. Returns FALSE and an error if file already exists

  56. How to find the position of the first occurrence of a substring in a string
    strpos() is used to find the position of the first occurrence of a substring in a string

  57. What is PEAR?
    PEAR is a framework and distribution system for reusable PHP components.The project seeks to provide a structured library of code, maintain a system for distributing code and for managing code packages, and promote a standard coding style.PEAR is broken into three classes: PEAR Core Components, PEAR Packages, and PECL Packages. The Core Components include the base classes of PEAR and PEAR_Error, along with database, HTTP, logging, and e-mailing functions. The PEAR Packages include functionality providing for authentication, networking, and file system features, as well as tools for working with XML and HTML templates.

  58. Distinguish between urlencode and urldecode?
    This method is best when encode a string to used in a query part of a url. it returns a string in which all non-alphanumeric characters except -_. have replece with a percentege(%) sign . the urldecode->Decodes url to encode string as any %and other symbole are decode by the use of the urldecode() function.

  59. What are the different errors in PHP?
    In PHP, there are three types of runtime errors, they are:
    Warnings:
    These are important errors. Example: When we try to include () file which is not available. These errors are showed to the user by default but they will not result in ending the script.
    Notices:
    These errors are non-critical and trivial errors that come across while executing the script in PHP. Example: trying to gain access the variable which is not defined. These errors are not showed to the users by default even if the default behavior is changed.
    Fatal errors:
    These are critical errors. Example: instantiating an object of a class which does not exist or a non-existent function is called. These errors results in termination of the script immediately and default behavior of PHP is shown to them when they take place. Twelve different error types are used to represent these variations internally.

List all default posts (with proper_pagination) in WordPress

To list all default posts in WordPress with proper pagination, you can use the WordPress Query API and pagination functions. Below is an example code snippet to display all posts with pagination in a WordPress theme:

Setting Up the Query with Pagination

Add this code to a template file, such as index.php, archive.php, or a custom template:

get_header();

// Define the number of posts per page
$posts_per_page = 10;

// Get the current page number
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

// Set up a new query for posts
$args = array(
    'post_type'      => 'post',
    'posts_per_page' => $posts_per_page,
    'paged'          => $paged,
);

$query = new WP_Query($args);

if ($query->have_posts()) :
    while ($query->have_posts()) : $query->the_post();
        the_excerpt();
    endwhile;

    // Display pagination
    echo '';
else :
    echo '

' . __('No posts found.', 'textdomain') . '

'; endif; // Reset post data wp_reset_postdata(); get_footer();

get post based on meta field content in WordPress

Solution for : Get post based on meta field content in WordPress.

The important thing is that we are querying for posts using at least the three criteria of the post type, meta key, and meta value.

For example, let's assume wer custom post type is just called "player" And, each 'player' post has a meta field attached called "player_team"

we could then query for those posts using something like this:

 
$teamname = ""; // the player's team that we're querying for

$myquery = new WP_Query( "post_type=player&meta_key=player_team&meta_value=$teamname&order=ASC" );

Create WordPress Page that redirects to another URL

Solution for : Create WordPress Page that redirects to another URL

we can accomplish this two ways, both of which need to be done through editing our template files.

The first one is just to add an html link to our navigation where ever we want it to show up.

The second (and my guess, the one we're looking for) is to create a new page template, which isn't too difficult if we have the ability to create a new .php file in our theme/template directory. Something like the below code should do:

 

/*  
Template Name: Page Redirect
*/ 

header('Location: http://www.name-of-new-site-where-we-have-to-redirect.com');
exit();

Where the template name is whatever we want to set it too and the url in the header function is the new url we want to direct a user to. After we modify the above code to meet our needs, save it in a php file in our active theme folder to the template name. So, if we leave the name of our template "Page Redirect" name the php file page-redirect.php.

After that's been saved, log into our WordPress backend, and create a new page. we can add a title and content to the body if we'd like, but the important thing to note is that on the right hand side, there should be a drop down option for we to choose which page template to use, with default showing first. In that drop down list, there should be the name of the new template file to use. Select the new template, publish the page, and we should be golden.

How do we check if a string contains a specific word in PHP?

Solution for : How do we check if a string contains a specific word in PHP?

We can use the strpos() function which is used to find the occurrence of one string inside another one:

 
$a = 'How are you?';
if (strpos($a, 'are') !== false) {
    echo 'true';
}

Note that the use of !== false is deliberate; strpos() returns either the offset at which the needle string begins in the haystack string, or the boolean false if the needle isn't found. Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like !strpos($a, 'are').

Display all post meta keys and meta values of the same post ID in wordpress

Solution for : Display all post meta keys and meta values of the same post ID in wordpress

Get the meta for all keys:

$meta = get_post_meta($post_id);

Get the meta for a single key:

$key_1_values = get_post_meta( 76, 'key_1' );

For example:

$myvals = get_post_meta($post_id);

foreach($myvals as $key=>$val)
{
    echo $key . ' : ' . $val[0] . '
'; }

For reference: See Codex

Programmatically creating new order in Woocommerce

Solution for : Programmatically creating new order in Woocommerce

We can create new order in Woocommerce using be hook.

add_action('woocommerce_checkout_process', 'create_vip_order');

function create_vip_order() {

  global $woocommerce;

  $address = array(
      'first_name' => '111Joe',
      'last_name'  => 'Conlin',
      'company'    => 'Speed Society',
      'email'      => 'joe@testing.com',
      'phone'      => '760-555-1212',
      'address_1'  => '123 Main st.',
      'address_2'  => '104',
      'city'       => 'San Diego',
      'state'      => 'Ca',
      'postcode'   => '92121',
      'country'    => 'US'
  );

  // Now we create the order
  $order = wc_create_order();

  // The add_product() function below is located in /plugins/woocommerce/includes/abstracts/abstract_wc_order.php
  $order->add_product( get_product('275962'), 1); // This is an existing SIMPLE product
  $order->set_address( $address, 'billing' );
  //
  $order->calculate_totals();
  $order->update_status("Completed", 'Imported order', TRUE);  
}

Make sure the product id given should exists in the system.

WooCommerce: Finding the products in database

Solution for : WooCommerce: Finding the products in database

Products are located mainly in 2 tables:

  • wp_posts table with a post_type like product or product_variation,

  • wp_postmeta table with the corresponding post_id by product (the product ID).

Product types, categories, subcategories, tags, attributes and all other custom taxonomies are located in the following tables:

  • wp_terms

  • wp_termmeta

  • wp_term_taxonomy

  • wp_term_relationships

  • wp_woocommerce_termmeta

  • wp_woocommerce_attribute_taxonomies (for product attributes only)

Product types are handled by custom taxonomy product_type with the following default terms:

  • simple
  • grouped
  • variable
  • external

Since Woocommerce 3+ a new custom taxonomy named product_visibility handle:

  • The product visibility with the terms exclude-from-search and exclude-from-catalog
  • The feature products with the term featured
  • The stock status with the term outofstock
  • The rating system with terms from rated-1 to rated-5

Particular feature: Each product attribute is a custom taxonomy…

References:

How to integrate WordPress template with CodeIgniter

Solution for : How can CodeIgniter and WordPress be integrated such that the look and feel/template of the WordPress blog is carried over to the CodeIgniter-created pages?

First step is to move CodeIgniter and the WordPress files in their own directory.

After that, put the following line at the top of your CodeIgniter's index.php file. Change the path to wp-blog-header.php as needed to point to your WordPress's root directory.

 
 require('../wp-blog-header.php');

Then, you can use the following functions inside your views:

 
 get_header();
 get_sidebar();
 get_footer();

Other helper functions can also be found in WordPress's documentation which can assist you in integrating the design.

Get WordPress Post ID from Post title

Solution for : Get WordPress Post ID from Post title.

Just a quick note for anyone who stumbles across this: get_page_by_title() can now handle any post type.
The $post_type parameter has been added in WP 3.0.

How to display Woocommerce product price by ID number on a custom page?

Solution for : How to display Woocommerce product price by ID number on a custom page?

If you have the product's ID you can use that to create a product object:

$_product = wc_get_product( $product_id );

Then from the object you can run any of WooCommerce's product methods.

 
$_product->get_regular_price();
$_product->get_sale_price();
$_product->get_price(); 

Removing <p> and <br/> tags in WordPress posts

Solution for : Removing <p> and <br/> tags in WordPress posts

This happens because of WordPress's wpautop. Simply add below line of code in your theme's functions.php file

remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );

For more information: http://codex.wordpress.org/Function_Reference/wpautop

How do you add a WordPress admin page without adding it to the menu?

Solution for : How do you add a WordPress admin page without adding it to the menu?

Best solution here http://wordpress.org/support/topic/add-backend-page-without-menu-item

use add_submenu_page with parent slug = null

WordPress: Disable “Add New” on Custom Post Type

Solution for : WordPress: Disable “Add New” on Custom Post Type

There is a meta capability create_posts that is not documented but is used by WordPress to check before inserting the various 'Add New' buttons and links. In your custom post type declaration, add capabilities (not to be confused with cap) and then set it to false as below.

register_post_type( 'custom_post_type_name', array(
  'capability_type' => 'post',
  'capabilities' => array(
    'create_posts' => 'do_not_allow', // false < WP 4.5, credit @Ewout
  ),
  'map_meta_cap' => true, // Set to `false`, if users are not allowed to edit/delete existing posts
));

wp_nav_menu change sub-menu class name?

Solution for : wp_nav_menu change sub-menu class name?

There is no option for this, but you can extend the 'walker' object that Wordpress uses to create the menu HTML. Only one method needs to be overridden:

class My_Walker_Nav_Menu extends Walker_Nav_Menu {
  function start_lvl(&$output, $depth) {
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent <ul class=\ "my-sub-menu\ ">\n";
  }
}

Then you just pass an instance of your walker as an argument to wp_nav_menu like so:

'walker' => new My_Walker_Nav_Menu()

Wordpress Get the Page ID outside the loop

Solution for : Wordpress Get the Page ID outside the loop

Since 3.1 - recommended!

// Since 3.1 - recommended!
$page_object = get_queried_object();
$page_id     = get_queried_object_id();

"Dirty" pre 3.1

// "Dirty" pre 3.1
global $wp_query;

$page_object = $wp_query->get_queried_object();
$page_id     = $wp_query->get_queried_object_id();

How to get last inserted row ID from wordpress database?

Solution for : How to get last inserted row ID from wordpress database?

Straight after the $wpdb->insert() that does the insert, do this:

$lastid = $wpdb->insert_id;

More information about how to do things the wordpress way can be found in the wordpress codex. The details above were found here on the wpdb class page

Wordpress asking for my FTP credentials to install plugins

Solution for : Wordpress asking for my FTP credentials to install plugins

Try to add the code in wp-config.php:

define('FS_METHOD', 'direct');

What does apply_filters(…) actually do in WordPress?

Solution for : What does apply_filters(…) actually do in WordPress?

apply_filters($tag, $value) passes the 'value' argument to each of the functions 'hooked' (using add_filter) into the specified filter 'tag'. Each function performs some processing on the value and returns a modified value to be passed to the next function in the sequence.

For example, by default (in WordPress 2.9) the the_content filter passes the value through the following sequence of functions:

  • wptexturize
  • convert_smilies
  • convert_chars
  • wpautop
  • shortcode_unautop
  • prepend_attachment
  • do_shortcode

How do I add a simple jQuery script to WordPress?

Solution for : How do I add a simple jQuery script to WordPress?

After much searching, I finally found something that works with the latest WordPress. Here are the steps to follow:

1) Find your theme's directory, create a folder in the directory for your custom js (custom_js in this example).

2)Put your custom jQuery in a .js file in this directory (jquery_test.js in this example).

3)Make sure your custom jQuery .js looks like this:

(function($) {
$(document).ready(function() {
$('.your-class').addClass('do-my-bidding');
})
})(jQuery);

4)Go to the theme's directory, open up functions.php

5)Add some code near the top that looks like this:


//this goes in functions.php near the top
function my_scripts_method() {
// register your script location, dependencies and version
   wp_register_script('custom_script',
   get_template_directory_uri() . '/custom_js/jquery_test.js',
   array('jquery'),
   '1.0' );
 // enqueue the script
  wp_enqueue_script('custom_script');
  }
add_action('wp_enqueue_scripts', 'my_scripts_method');

6) Check out your site to make sure it works!

How to get WordPress post featured image url

Solution for : How to get WordPress post featured image url?

Below the simple code. It works for me.

 if (has_post_thumbnail( $post->ID ) ){
     $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );
  $imageurl= $image[0]; //image url
 }

Best place to insert the Google Analytics code in wordpress site

Solution for : Best place to insert the Google Analytics code

Google used to recommend putting it just before the tag, because the original method they provided for loading ga.js was blocking. The newer async syntax, though, can safely be put in the head with minimal blockage, so the current recommendation is just before the tag.

will add a little latency; in the footer will reduce the number of pageviews recorded at some small margin. It's a tradeoff. ga.js is heavily cached and present on a large percentage of sites across the web, so its often served from the cache, reducing latency to almost nil.

As a matter of personal preference, I like to include it in the , but its really a matter of preference.

TypeError: $ is not a function when calling jQuery function

Solution for : TypeError: $ is not a function when calling jQuery function

By default when you enqueue jQuery in Wordpress you must use jQuery, and $ is not used (this is for compatibility with other libraries).

Your solution of wrapping it in function will work fine, or you can load jQuery some other way (but that's probably not a good idea in Wordpress).

If you must use document.ready, you can actually pass $ into the function call:

jQuery(function ($) { ...

How to add a PHP page to WordPress?

Solution for : I want to create a custom page for my WordPress blog that will execute my PHP code in it, whilst remaining a part of the overall site CSS/theme/design.

First, duplicate post.php or page.php in your theme folder (under /wp-content/themes/themename/).

Rename the new file as templatename.php (where templatename is what you want to call your new template). To add your new template to the list of available templates, enter the following at the top of the new file:

/*
Template Name: Name of Template
*/

You can modify this file (using PHP) to include other files or whatever you need.

Then create a new page in your WordPress blog, and in the page editing screen you'll see a Template drop-down in the Attributes widget to the right. Select your new template and publish the page.

Your new page will use the PHP code defined in templatename.php

Create a folder if it doesn't already exist

Solution for: How can we create a folder if it doesn't already exist?

Below the simple lines to Create a folder if it doesn't already exist.

if (!file_exists('path/to/directory')) {
    mkdir('path/to/directory', 0777, true);
}

Note that 0777 is already the default mode for directories and may still be modified by the current umask.

Magento - do not display prices to users not logged in

If we have to hide prices for guest users everywhere.

We just have to follow below steps-

Open app/design/frontend/base/default/template/catalog/product/ folder and copy price.phtml file to the app/design/frontend/theme_package/your_theme/template/catalog/product/ folder and then Place the following code on top of it:
if(!Mage::getSingleton('customer/session')->isLoggedIn()){
echo '
'; return; }

Display an estimated delivery date range based on cart item stock in WooCommerce

If you are trying to output an estimated delivery date in the cart based on the stock status of the products in the cart.

The code below, will check the stock quantity of each item in the cart.

1) If all cart items are "in stock" it will echo an estimated shipping time of 1 to 4 working days given as a date.

2) If one cart items is "out of stock" it will echo an estimated shipping time of 14 to 21 working days given as a date.

But I will not recognize holidays

Here is that code:

add_filter ( 'woocommerce_cart_collaterals', 'lieferzeit');
function lieferzeit() {

    $all_items_in_stock = true; // initializing

    // Iterating through cart items (to get the stock info)
    foreach (WC()->cart->get_cart() as $cart_item) {
        // The cart item stock quantity
        $stock = $cart_item['data']->get_stock_quantity();

        if( $stock <= 0 ){
            // if an item is out of stock
            $all_items_in_stock = false;
            break; // We break the loop
        }
    }

    // Items "in stock" (1 to 4 week days)
    if( $all_items_in_stock ){
        for( $start=0, $count=-1 ; $count < 4; $start++ ){
            $weekdays = date('w', strtotime("+$start days"));
            if( $weekdays > 0 && $weekdays < 6 ){
                $count++;
            echo date('D j (w)', strtotime("+$start days")).', ';
                if($count == 1){
                    $from = date('D. j/n', strtotime("+$start days") );
                } elseif($count == 4) {
                    $to = date('D. j/n', strtotime("+$start days") );
                }
            }
        }
    } else { // 1 is Items Out of stock (14 to 21 week days)
        for( $start=0, $count=-1 ; $count < 21; $start++ ){
            $weekdays = date('w', strtotime("+$start days"));
            if( $weekdays > 0 && $weekdays < 6 ){
                $count++;
                if($count == 14){
                    $from = date('D. j/n', strtotime("+$start days") );
                } elseif($count == 21) {
                    $to = date('D. j/n', strtotime("+$start days") );
                }
            }
        }
    }
    ## TRANSLATION ##

    // DAYS IN ENGLISH (Source)
    $days_en = array('Mon','Tue','Wed','Thu','Fri');

    // TRANSLATE the DAYS in GERMAN (replacement)
    $days_ge = array('Mmm','Ttt','Www','Thh','Fff');

    $from = str_replace( $days_en, $days_ge, $from );
    $to = str_replace( $days_en, $days_ge, $to );

    ## OUTPUT ##

    echo "

Estimated shipping $from - $to"; }

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works

Enable free shipping for two or more cart items in Woocommerce

In Woocommerce, if we want to offer free shipping based on the number of cart items.

If we want to do is: buy 2 of anything and get free shipping.

We can do this using below steps

add_filter( 'woocommerce_shipping_free_shipping_is_available', 'free_shipping_for_x_cart_items', 10, 3 );
function free_shipping_for_x_cart_items( $is_available, $package, $shipping_method ) {
    $item_count = WC()->cart->get_cart_contents_count();

    if ( $item_count == 1 ) {
        $notice = __("Add one more for free shipping");
        $is_available = false;
    } elseif ($item_count > 1) {
        $notice = __("You get free shipping");
        $is_available = true;
    }

    if ( isset($notice) ) {
        wc_add_notice( $notice, 'notice' );
    }
    return $is_available;
}

This code goes in function.php file of your active child theme (or active theme). Tested and works.

The WC_Cart method get_cart_contents_count() get the count of all items (including quantities).

To get the count of different cart items (without including quantities), replace the line:

$item_count = WC()->cart->get_cart_contents_count();

with this one:

$item_count = sizeof($package['contents']);

Contact form 7 - thank you page with summary

If we need a customized thank you page which will be showed after submitting contact form (contactform7), the form will show the name and email address entered by user.

Below is the example thank you page:

Thank you xxx : someone from our office will get in touch with you via xxx@example.com within 24 hours.

We can figure out a solution by utilizing the Additional Settings of contact form 7 and placed following code in these settings.

Note: It only works for Ajax based form.

on_sent_ok: "var name = $('.wpcf7 input[name=your-name]').val();var email = $('.wpcf7 input[name=your-email]').val();$('.wpcf7').hide();$('.entry-title').html('Thank you');$('.entry-content').html('thank you '+name+' : someone from our office will get in touch with you via '+email+' within 24 hours.');"

Open up the contact form configuration page and paste above code as shown below:

Sample Output as below:

Solution for: Error: Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress

Solution for: Error: Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress

Sometimes our website built using WordPress, there was below error:

Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress

If you also have a WordPress website where you are facing the error Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress when attempting to login, below is the very easy solution.

Temporary Solution:

After you are getting the this on the login page, you can simply refresh the page and login again. You should be able to login.

Permanent Solution:

Add the following line at the end of the wp-config.php file.

define('COOKIE_DOMAIN', $_SERVER['HTTP_HOST'] );

That's it.

After adding the above line in wp-config.php file, we do not get the error again.

Related Reference: https://codex.wordpress.org/Editing_wp-config.php

Number Pattern - program 3

Number Pattern

54321
4321
321
21
1

C program

#include<stdio.h>
int main()
{
    int i, j;
    for(i=5;i>=1;i--)
    {
        for(j=i;j>=1;j--)
        {
            printf("%d",j);
        }
        printf("\n");
    }

    return 0;
}

Number Pattern - program 2

Number Pattern

12345
2345
345
45
5

C program

#include<stdio.h>
int main()
{
    int i, j;
    for(i=1;i<=5;i++)
    {
        for(j=i;j<=5;j++)
        {
            printf("%d",j);
        }
        printf("\n");
    }

    return 0;
}

Number Pattern - program 1

Number Pattern

12345
1234
123
12
1

C program

#include<stdio.h>
int main()
{
    int i, j;
    for(i=5;i>=1;i--)
    {
        for(j=1;j<=i;j++)
        {
            printf("%d",j);
        }
        printf("\n");
    }

    return 0;
}

Star Patterns - C programs

Star Patterns - some very useful examples of Star Patterns C program are as follows.

Star Pattern - 1

    *
   *** 
  *****
 *******
*********

C program

#include<stdio.h>

int main()
{
    int i, j, k;
    for(i=1;i<=5;i++)
    {
        for(j=i;j<5;j++)
        {
            printf(" ");
        }
        for(k=1;k < (i*2);k++)
        {
                printf("*");
        }
        printf("\n");
    }

    return 0;
} 
=============================================

Star Pattern - 2

*********
 *******
  *****
   ***   
    *

C program

#include<stdio.h>

int main()
{
    int i, j, k;
    for(i=5;i>=1;i--)
    {
        for(j=5;j>i;j--)
        {
                printf(" ");
        }
        for(k=1;k < (i*2);k++)
        {
                printf("*");
        }
        printf("\n");
    }

    return 0;
} 
=============================================

Star Pattern - 3

**********
****  ****
***    ***
**      **
*        *
**      **
***    ***
****  ****
**********

C program

#include<stdio.h>

int main()
{
    int i, j, k;
    for(i=1;i<=5;i++)
    {
        for(j=1;j<=6-i;j++)
        {
            printf("*");
        }
        for(k=1;k < i;k++)
        {
            printf("  ");
        }
        for(j=1;j<=6-i;j++)
        {
            printf("*");
        }
        printf("\n");
    }
    for(i=2;i<=5;i++)
    {
        for(j=1;j<=i;j++)
        {
            printf("*");
        }
        for(k=1;k <= 5-i;k++)
        {
            printf("  ");
        }
        for(j=1;j<=i;j++)
        {
            printf("*");
        }
        printf("\n");
    }

    return 0;
} 
=============================================

Star Pattern - 4

    *
   *** 
  *****
 *******
*********
 *******
  *****
   ***   
    *

C program

#include<stdio.h>

int main()
{
    int i, j, k;
    for(i=1;i<=5;i++)
    {
        for(j=i;j<5;j++)
        {
            printf(" ");
        }
        for(k=1;k < (i*2);k++)
        {
                printf("*");
        }
        printf("\n");
    }
    for(i=4;i>=1;i--)
    {
        for(j=5;j>i;j--)
        {
                printf(" ");
        }
        for(k=1;k < (i*2);k++)
        {
                printf("*");
        }
        printf("\n");
    }

    return 0;
} 

=============================================

Star Pattern - 5

*
**
***
****
*****

C program

#include<stdio.h>

int main()
{
    int i, j;
    for(i=1;i<=5;i++)
    {
        for(j=1;j<=i;j++)
        {
            printf("*");
        }
        printf("\n");
    }

    return 0;
}
=============================================

Star Pattern - 6

*****
****
***
**
*

C program

#include<stdio.h>

int main()
{
    int i, j;
    for(i=5;i>=1;i--)
    {
        for(j=1;j<=i;j++)
        {
            printf("*");
        }
        printf("\n");
    }

    return 0;
}
=============================================

Star Pattern - 7

    *
   **
  ***
 ****
*****

C program

#include<stdio.h>

int main()
{
    int i, j, k;
    for(i=5;i >= 1;i--)
    {
        for(j=1;j < i;j++)
        {
            printf(" ");
        }
        for(k=5;k >= i;k--)
        {
            printf("*");
        }
        printf("\n");
    }

    return 0;
}
=============================================

Star Pattern - 8

*****
 **** 
  *** 
   ** 
    *

C program

#include<stdio.h>

int main()
{
    int i, j, k;
    for(i=5;i>=1;i--)
    {
        for(j=5;j>i;j--)
        {
            printf(" ");
        }
        for(k=1;k <= i;k++)
        {
            printf("*");
        }
        printf("\n");
    }

    return 0;
}
=============================================

Star Pattern - 9

 
    *
   * *
  *   *
 *     *
*       *
 *     *
  *   *
   * *
    *

C program

#include<stdio.h>
int main()
{
    int i, j;
    
    for(i=1; i<=5; i++)
    {
        for(j=5; j>i; j--)
        {
            printf(" ");
        }
      printf("*");
        for(j=1; j<(i-1)*2; j++)
        {
            printf(" ");
        }
        if(i==1) printf("\n");
      else printf("*\n");
    }
    
    for(i=4; i>=1; i--)
    {
        for(j=5; j>i; j--)
        {
            printf(" ");
        }
      printf("*");
        for(j=1; j<(i-1)*2; j++)
        {
            printf(" ");
        }
        if(i==1) printf("\n");
      else printf("*\n");
    }    
    
    return 0;
}
=============================================

Alphabet Patterns - C programs

Alphabet Patterns - some vey useful examples of Alphabet Patterns C program are as follows.

Alphabet Pattern - 1

A
AB
ABC
ABCD
ABCDE

C program

#include<stdio.h>

int main()
{
    int i, j;
    for(i=1;i<=5;i++)
    {
        for(j=1;j<=i;j++)
        {
            printf("%c",'A' + j-1);
        }
        printf("\n");
    }

    return 0;
}

Alphabet Pattern - 2

E
DE
CDE
BCDE
ABCDE

C program

#include<stdio.h>

int main()
{
    int i, j;
    for(i=5;i>=1;i--)
    {
        for(j=i;j<=5;j++)
        {
            printf("%c",'A' + j-1);
        }
        printf("\n");
    }

    return 0;
}

Alphabet Pattern - 3

A
BA
CBA
DCBA
EDCBA

C program

#include<stdio.h>

int main()
{
    int i, j;
    for(i=1;i<=5;i++)
    {
        for(j=i;j>=1;j--)
        {
            printf("%c",'A' + j-1);
        }
        printf("\n");
    }

    return 0;
}

Alphabet Pattern - 4

E
ED
EDC
EDCB
EDCBA

C program

#include<stdio.h>

int main()
{
    int i, j;
    for(i=5;i>=1;i--)
    {
        for(j=5;j>=i;j--)
        {
            printf("%c",'A' + j-1);
        }
        printf("\n");
    }

    return 0;
}

Alphabet Pattern - 5

ABCDE
ABCD
ABC
AB
A

C program

#include<stdio.h>

int main()
{
    int i, j;
    for(i=5;i>=1;i--)
    {
        for(j=1;j<=i;j++)
        {
            printf("%c",'A' + j-1);
        }
        printf("\n");
    }

    return 0;
}

Alphabet Pattern - 6

ABCDE
BCDE
CDE
DE
E

C program

#include<stdio.h>

int main()
{
    int i, j;
    for(i=1;i<=5;i++)
    {
        for(j=i;j<=5;j++)
        {
            printf("%c", 'A'-1 + j);
        }
        printf("\n");
    }

    return 0;
}

Alphabet Pattern - 7

EDCBA
DCBA
CBA
BA
A

C program

#include<stdio.h>
int main()
{
    int i, j;
    for(i=5;i>=1;i--)
    {
        for(j=i;j>=1;j--)
        {
            printf("%c",'A'-1 + j);
        }
        printf("\n");
    }

    return 0;
}

Alphabet Pattern - 8

EDCBA
EDCB
EDC
ED
E

C program

#include<stdio.h>
int main()
{
    int i, j;
    for(i=1;i<=5;i++)
    {
        for(j=5;j>=i;j--)
        {
            printf("%c",'A'-1 + j);
        }
        printf("\n");
    }

    return 0;
}

Alphabet Pattern - 9

A
BB
CCC
DDDD
EEEEE

C program

#include<stdio.h>
int main()
{
    int i, j;
    for(i=1;i<=5;i++)
    {
        for(j=1;j<=i;j++)
        {
            printf("%c",'A'-1 + i);
        }
        printf("\n");
    }

    return 0;
} 

Alphabet Pattern - 10

E
DD
CCC
BBBB
AAAAA

C program

#include<stdio.h>
int main()
{
    int i, j;
    for(i=5;i>=1;i--)
    {
        for(j=5;j>=i;j--)
        {
            printf("%c",'A'-1 + i);
        }
        printf("\n");
    }

    return 0;
} 

Alphabet Pattern - 11

EEEEE
DDDD
CCC
BB
A

C program

#include<stdio.h>
int main()
{
    int i, j;
    for(i=5;i>=1;i--)
    {
        for(j=1;j<=i;j++)
        {
            printf("%c",'A'-1 + i);
        }
        printf("\n");
    }

    return 0;
}

Alphabet Pattern - 12

AAAAA
BBBB
CCC
DD
E

C program

#include<stdio.h>
int main()
{
    int i, j;
    for(i=1;i<=5;i++)
    {
        for(j=5;j>=i;j--)
        {
            printf("%c",'A'-1 + i);
        }
        printf("\n");
    }

    return 0;
} 

Series Program- 1 3 8 15 27 50 92 169 311

Below is C program for Series Program- 1 3 8 15 27 50 92 169 311

Program:

/* Series Program-1 3 8 15 27 50 92 169 311 */
void main()
{
    int a=1, b=3, c=4, n=10, sum, i;
    printf("%d %d ",a,b,c);
    for(i=4; i<=n; i++)
    {
        sum = a+b+c;
        printf("%d ",sum);
      a = b;
      b = c;
      c = sum;
    }
}

Series Program- 2 15 41 80 132 197 275 366 470 587

Below is C program for Series Program- 2 15 41 80 132 197 275 366 470 587

Program:

/* Series Program-2 15 41 80 132 197 275 366 470 587  */
int main()
{
    int a=2,i,n=10;
    for(i=1;i<=n;i++)
    {
        printf("%d ",a);
        a+=13*i;
    }
    return 0;
}

Series Program- 1 2 3 6 9 18 27 54...

Below is C program for Series Program- 1 2 3 6 9 18 27 54...

Program:

/* Series Program-1 2 3 6 9 18 27 54... */
int main()
{
    int a=1,b=2,i,n=10;
    printf("%d %d ",a, b);
    for(i=3;i<=n;i++)
    {
        if(i%2==1)
        {
            a=a*3;
            printf("%d ",a);
        }
        else
        {
            b=b*3;
            printf("%d ",b);
        }
    }
    return 0;
}

Series Program- 1/2 - 2/3 + 3/4 - 4/5 + 5/6 - ...... n

Below is C program for Series Program- 1/2 - 2/3 + 3/4 - 4/5 + 5/6 - ...... n

Program:

/* Series Program-1/2 - 2/3 + 3/4 - 4/5 + 5/6 - ...... n*/
int main()
{
    double i, n,sum=0;
    n=10;
    for(i=1;i<=n;i++)
    {
        if ((int)i%2==1)
            sum+=i/(i+1);
        else
            sum-=i/(i+1);
    }
    printf("Sum: %lf",sum);
    return 0;
}

Series Program- [(1^1)/1!] + [(2^2)/2!] + [(3^3)/3!] + [(4^4)/4!] + [(5^5)/5!] + ... + [(n^n)/n!]

Below is C program for Series Program- [(1^1)/1!] + [(2^2)/2!] + [(3^3)/3!] + [(4^4)/4!] + [(5^5)/5!] + ... + [(n^n)/n!]

Program:

/* Series Program-[(1^1)/1!] + [(2^2)/2!] + [(3^3)/3!] + [(4^4)/4!] + [(5^5)/5!] + ... + [(n^n)/n!]*/
double power(int a, int b)
{
    long i, p=1;
    for(i=1;i<=b;i++)
    {
        p=p*a;
    }
    return p;
}

double fact(int n)
{
    long i, f=1;
    for(i=1;i<=n;i++)
    {
        f=f*i;
    }
    return f;
}

int main()
{
    long i,n;
    double sum=0;
    n=5;
    for(i=1;i<=n;i++)
    {
        sum=sum+power(i,i)/fact(i);
    }
    printf("Sum: %lf",sum);
    return 0;
}


Series Program- [(1^1)/1] + [(2^2)/2] + [(3^3)/3] + [(4^4)/4] + [(5^5)/5] + ... + [(n^n)/n]

Below is C program for Series Program- [(1^1)/1] + [(2^2)/2] + [(3^3)/3] + [(4^4)/4] + [(5^5)/5] + ... + [(n^n)/n]

Program:

/* Series Program-[(1^1)/1] + [(2^2)/2] + [(3^3)/3] + [(4^4)/4] + [(5^5)/5] + ... + [(n^n)/n]*/
long power(int a, int b)
{
    long i, p=1;
    for(i=1;i<=b;i++)
    {
        p=p*a;
    }
    return p;
}

int main()
{
    long i,n;
    double sum=0;
    n=5;
    for(i=1;i<=n;i++)
    {
        sum=sum+(power(i,i)/i);
    }
    printf("Sum: %lf",sum);
    return 0;
}

Series Program- 1!/1) + (2!/2) + (3!/3) + (4!/4) + (5!/5) + ... + (n!/n)

Below is C program for Series Program- 1!/1) + (2!/2) + (3!/3) + (4!/4) + (5!/5) + ... + (n!/n)

Program:

/* Series Program- 1!/1) + (2!/2) + (3!/3) + (4!/4) + (5!/5) + ... + (n!/n)*/
long fact(int n)
{
    long i, f=1;
    for(i=1;i<=n;i++)
    {
        f=f*i;
    }
    return f;
}

int main()
{
    long i,n;
    double sum=0;
    n=5;
    for(i=1;i<=n;i++)
    {
        sum=sum+(fact(i)/i);
    }
    printf("Sum: %lf",sum);
    return 0;
}


Series Program- (1^1) + (2^2) + (3^3) + (4^4) + (5^5) + ... + (n^n)

Below is C program for Series Program- (1^1) + (2^2) + (3^3) + (4^4) + (5^5) + ... + (n^n)

Program:

/* Series Program- (1^1) + (2^2) + (3^3) + (4^4) + (5^5) + ... + (n^n)*/
long power(int a, int b)
{
    long i, p=1;
    for(i=1;i<=b;i++)
    {
        p=p*a;
    }
    return p;
}

int main()
{
    long i,n,sum=0;
    n=5;
    for(i=1;i<=n;i++)
    {
        sum=sum+power(i,i);
    }
    printf("Sum: %d",sum);
    return 0;
}

Series Program- 1! + 2! + 3! + 4! + 5! + ... + n!

Below is C program for Series Program- 1! + 2! + 3! + 4! + 5! + ... + n!

Program:

/* Series Program- 1! + 2! + 3! + 4! + 5! + ... + n! */

long fact(int n)
{
    long i, f=1;
    for(i=1;i<=n;i++)
    {
        f=f*i;
    }
    return f;
}

int main()
{
    long i,n,sum=0;
    n=5;
    for(i=1;i<=n;i++)
    {
        sum=sum+fact(i);
    }
    printf("Sum: %d",sum);
    return 0;
}

Series Program- (1) + (1+2) + (1+2+3) + (1+2+3+4) + ... + (1+2+3+4+...+n)

Below is C program for Series Program- (1) + (1+2) + (1+2+3) + (1+2+3+4) + ... + (1+2+3+4+...+n)

Program:

/* Series Program- (1) + (1+2) + (1+2+3) + (1+2+3+4) + ... + (1+2+3+4+...+n) */

int main()
{
    int i,j,n,sum=0;
    n=10;
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=i;j++)
        {
            sum+=j;
        }
    }
    printf("Sum: %d",sum);
    return 0;
}

Series Program- (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + ... + (n*n)

Below is C program for Series Program- (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + ... + (n*n)

Program:

/* Series Program- (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + ... + (n*n) */

int main()
{
    int i,n,sum=0;
    n=10;
    for(i=1;i<=n;i++)
    {
        sum+=i*i;
    }
    printf("Sum: %d",sum);
    return 0;
}

Series Program- 1 + 2 + 3 + 4 + 5 + ... + n

Below is C program for Series Program- 1 + 2 + 3 + 4 + 5 + ... + n.

Program:

/* Series Program- 1 + 2 + 3 + 4 + 5 + ... + n */

int main()
{
    int i,n,sum=0;
    n=10;
    for(i=1;i<=n;i++)
    {
        sum+=i;
    }
    printf("Sum: %d",sum);
    return 0;
}

C program to Towers of Hanoi by recursion

Below is C program to Towers of Hanoi by recursion .

Program:

/* Towers of Hanoi by recursion */

#include<stdio.h>
void toh(int,char,char,char);

int main()
{
 int n=3;
 toh(n,'A','B','C');
 return 0;
}

void toh(int n,char a,char b,char c)
{
 if(n==1)
  printf("\nMoved from %c to %c",a,c);
 else
 {
  toh(n-1,a,c,b);
  toh(1,a,' ',c);
  toh(n-1,b,a,c);
 }
}

C program to Decimal to Binary by Recursion

Below is C program to Decimal to Binary by Recursion.

Program:

/* Binary by recursion */

#include<stdio.h>
void binary(long);
int main()
{
 long n;
 printf("Type a value : ");
 scanf("%ld",&n);
 binary(n);
 return 0;
}

void binary(long n)
{
 if(n>1)
  binary(n/2);
 printf("%ld",n%2);
}

C program to GCD by Recursion

Below is C program to Sum of GCD by Recursion .

Program:

/* GCD by recursion */

#include<stdio.h>
int gcd(int,int);

int main()
{
 int a,b;
 printf("Type 2 values to find GCD :\n");
 scanf("%d %d",&a,&b);
 printf("GCD : %d",gcd(a,b));
 return 0;
}

int gcd(int m,int n)
{
 if(n>m) return gcd(n,m);
 if(n==0) return m;
 return gcd(n,m%n);
}

C program to Sum of digit by Recursion

Below is C program to Sum of digit by Recursion .

Program:

/* Sum of digit by recursion */

#include<stdio.h>
int sod(int);

int main()
{
 int i;
 printf(" Type any value : ");
 scanf("%d",&i);
 printf("Sum of digit : %d",sod(i));
 return 0;
}

int sod(int n)
{
 if(n<1)
  return 0;
 return(n%10+sod(n/10));
}


C program to Reverse a Number by Recursion

Below is C program to Reverse a Number by Recursion.

Program:

/* Reverse by Recursion */

#include<stdio.h>
int rev(int,int);

int main()
{
 int a;
 printf("Type a value : ");
 scanf("%d",&a);
 printf("Reverse: %d",rev(a,0));
 return 0;
}

int rev(int i,int r)  
{
 if(i > 0)  
  return rev(i/10,(r*10)+(i%10));  
 return r;  
}


C program to Fibonacci by Recursion

Below is C program to Fibonacci by Recursion .

Program:

/* Fibonacci by Recursion */

#include<stdio.h>
int fib(int);

int main()
{
 printf("Type any value : ");
 printf("\nNth value: %d",fib(getche()-'0'));
 return 0;
}

int fib(int n)
{
 if(n<=1)
  return n;
 return(fib(n-1)+fib(n-2));
}

C program to Power by Recursion

Below is C program to Power by Recursion .

Program:

/* Power by Recursion */

#include<stdio.h>
int pow(int,int);

int main()
{
 int i,j;
 printf("Type two values : \n");
 scanf("%d %d",&i,&j);
 
 printf("i pow j = %d",pow(i,j));
 return 0;
}

int pow(int i,int j)
{
 if(j==1)
  return i;
 return (i*pow(i,j-1));
}

C program to Factorial by Recursion

Below is C program to Factorial by Recursion .

Program:

/* Factorial by Recursion */

#include<stdio.h>
int fact(int);

int main()
{
  int n;
  printf("Type any value : ");
  scanf("%d",&n);
  n=fact(n);
  printf("\nFactorial : %d ",n);
  return 0;
}

int fact(int x)
{
  if(x==1)
    return(x);
  else
   x=x*fact(x-1);
}

C program to File to File Copy using command line arguments

Below is C program to File Copy using command line arguments .

Program:

/* File Copy using command line arguments */

#include<stdio.h>
int main(int argc,char *argv[])
{
 FILE *fs,*ft;
 int ch;
 if(argc!=3)
 {
  printf("Invalide numbers of arguments.");
  return 1;
 }
 fs=fopen(argv[1],"r");
 if(fs==NULL)
 {
  printf("Can't find the source file.");
  return 1;
 }
 ft=fopen(argv[2],"w");
 if(ft==NULL)
 {
  printf("Can't open target file.");
  fclose(fs);
  return 1;
 }

 while(1)
 {
  ch=fgetc(fs);
  if (feof(fs)) break;
  fputc(ch,ft);
 }

 fclose(fs);
 fclose(ft);
 return 0;
}

C program to File to upper case using command line arguments

Below is C program to File to upper case using command line arguments .

Program:

/* File to upper case using command line arguments */

#include<stdio.h>
int main(int n,char *a[])
{
 int c;
 FILE *fr,*fw;

 if(n!=3)
 {
  printf("Invalide numbers of arguments.");
  return 1;
 }

 if((fr=fopen(a[1],"r"))==NULL)
 {
  printf("File can't be open.");
  return 1;
 }
 if((fw=fopen(a[2],"r+"))==NULL)
 {
  printf("File can't be open.");
  fclose(fr);
  return 1;
 }
 while(1)
 {
  c=fgetc(fr);
  if(feof(fr)) break;
  c=~c;
  fputc(c,fw);
 }
 fclose(fr);
 fclose(fw);
 return 0;
}

C program to Count characters of file

Below is C program to Count characters of file .

Program:

/* Count characters of file */

#include<stdio.h>
int main()
{
 FILE *fp;
 char a[10];
 long cnt=0;
 int c;

 printf("Type a file name : ");
 gets(a);
 
 if((fp=fopen(a,"r"))==NULL)
  printf("File dosen't exist.");
 else
 {
  while(1)
  {
   c=fgetc(fp);
   if(feof(fp)) break;
   cnt++;
  }
  printf("\nfile have %ld characters",cnt);
 }
 fclose(fp);
 return 0;
}

C program to Write to text file

Below is C program to Write to text file .

Program:

/* Write to text file */

#include<stdio.h>
int main()
{
 FILE *fp;
 char mystr[100];

 fp=fopen("mytext.txt","w");
 if(fp==NULL)
 {
  puts("Some error occured.");
  return 1;
 }

 printf("\nEnter some lines:\n");
 while(strlen(gets(mystr))>0)
 {
  fputs(mystr,fp);
  fputs("\n",fp);
 }
 fclose(fp);
 return 0;
}


C program to Read text file

Below is C program toRead text file .

Program:

/* Read text file */

#include<stdio.h>
int main()
{
 FILE *fp;
 int ch;
 
 fp=fopen("myfile.txt","r");
 if(fp==NULL)
 {
  printf("Can't find the source file.");
  return 1;
 } 
 while(1)
 {
  ch=fgetc(fp);
  if(feof(fp)) break;
  printf("%c",ch);
 } 
 fclose(fp);
 return 0;
}

C program to Sort array of 10 strings

Below is C program to Sort array of 10 strings.

Program:

/* Sort array of 10 strings. */

#include<string.h>
#include<stdio.h>


int main()
{
 int i,j;
 char str[10][10],temp[10];
 printf("Type 10 names :\n");
 for(i=0;i<10;i++)
 {
  // gets(str[i]);
  // fgets is a better option over gets to read multiword string .
  fgets(str[i], 10, stdin);
 }
 for(i=0;i<10;i++)
 {
  for(j=0;j<10-1-i;j++)
  {
   if(strcmpi(str[j],str[j+1])>0)
   {
    strcpy(temp,str[j]);
    strcpy(str[j],str[j+1]);
    strcpy(str[j+1],temp);
   }
  }
 }
   
 printf("\nSorted Names :\n");
 for(i=0;i<10;i++)
  puts(str[i]);
 return 0;
}

C program to Locate a word in String - STRSTR

Below is C program to Locate a word in String - STRSTR.

Program:

/* Locate a word in String - STRSTR */

#include<stdio.h>

int main()
{
 char str1[100], str2[100];
 int i,j,k;
 printf("Please enter first string: ");
 // gets(str1); 
 // fgets is a better option over gets to read multiword string .
 fgets(str1, 100, stdin);
 // Following can be added for extra precaution for '\n' character
 // if(str1[length(str1)-1] == '\n') str1[strlen(str1)-1]=NULL;

 printf("Please enter a word: ");
 // gets(str2); 
 fgets(str2, 100, stdin);
 // if(str2[length(str2)-1] == '\n') str2[strlen(str2)-1]=NULL;
 
 for(i=0;str1[i]!=NULL;i++)
 {
  for(k=i,j=0;str2[j]!=NULL;j++,k++)
   if(str1[k]!=str2[j])
    break;
  if(str2[j]==NULL)
  {
   printf("\"%s\" is the sub string of \"%s\" at %d location",str2,str1,k+1);
   i=-1;
   break;
  }
 }
 if(i!=-1)
  printf("\"%s\" is not the sub string of \"%s\"",str2,str1);

 return 0;
}
 


C program to Locate a character in String - STRCHR

Below is C program to Locate a character in String - STRCHR.

Program:

/* Locate a character in String - STRCHR */

#include<stdio.h>

int main()
{
 char str[500];
 int i;
 char ch;
 printf("Please enter your string: ");
 // gets(str); 
 // fgets is a better option over gets to read multiword string .
 fgets(str, 500, stdin);
 // Following can be added for extra precaution for '\n' character
 // if(str[length(str)-1] == '\n') str[strlen(str)-1]=NULL;

 printf("Please enter a character: ");
 getchar(ch); 
 
 for(i=0;str[i]!=NULL;i++)
 {
  if(str[i]==ch)
   break;
 }
 
 if(str[i] == NULL)
  printf("%c not found in %s",ch,str);
 else
  printf("\"%c\" found in \"%s\" at %d location",ch,str,i+1);

 return 0;
}

C program to String Concatenation - STRCAT

Below is C program to String Concatenation - STRCAT.

Program:

/* STRING CONCATENATION - STRCAT */

#include<stdio.h>

int main()
{
 char str1[500], str2[100];
 int i, j;
 printf("Please enter first string: ");
 // gets(str); 
 // fgets is a better option over gets to read multiword string .
 fgets(str1, 500, stdin);
 // Following can be added for extra precaution for '\n' character
 // if(str1[length(str1)-1] == '\n') str1[strlen(str1)-1]=NULL;

 printf("Please enter second string: ");
 // gets(str2); 
 fgets(str2, 100, stdin); 
 // if(str2[length(str2)-1] == '\n') str2[strlen(str2)-1]=NULL;
 
 for(i=0;str1[i]!=NULL;i++);
 for(j=0;str2[j]!=NULL;j++)
 {
  str1[i++]=str2[j];
 }
 str1[i]=NULL;
 
 printf("Concatenated string is: %s",str1);

 return 0;
}


C program to String Reverse - STRREV

Below is C program to String Reverse - STRREV.

Program:

/* STRING REVERSE - STRREV */

#include<stdio.h>

int main()
{
 char str[100];
 int i,j;
 char c;
 printf("Please enter a string: ");
 // gets(str); 
 // fgets is a better option over gets to read multiword string .
 fgets(str, 100, stdin);
 // Following can be added for extra precaution for '\n' character
 // if(str[length(str)-1] == '\n') str[strlen(str)-1]=NULL;
   
 for(i=0;str[i];i++);
 for(j=0,i--;j < i;j++,i--)
 {
  c=str[i];
  str[i]=str[j];
  str[j]=c;
 }

 printf("Reversed string is: %s",str);

 return 0;
}

C program to String Compare Ignore Case - STRICMP

Below is C program to String Compare Ignore Case - STRICMP.

Program:

/* STRING COMPARE IGNORE CASE - STRICMP */

#include<stdio.h>

int main()
{
 char str1[100], str2[100];
 int i, d=0, flag=0;
 char x,y;
 printf("Please enter first string: ");
 // gets(str1); 
 // fgets is a better option over gets to read multiword string .
 fgets(str1, 100, stdin);
 // Following can be added for extra precaution for '\n' character
 // if(str1[length(str1)-1] == '\n') str1[strlen(str1)-1]=NULL;

 printf("Please enter second string: ");
 // gets(str2); 
 fgets(str2, 100, stdin);
 // if(str2[length(str2)-1] == '\n') str2[strlen(str2)-1]=NULL;

 for(i=0;str1[i]!=NULL&&str2[i]!=NULL;i++)
 {
  x=str1[i];
  y=str2[i];
  if(x>='a'&&x<='z')
   x-=32;
  if(y>='a'&&y<='z')
   y-=32;
  if(x!=y)
  {
   break;
   flag=1;
  }
 }
 if(flag=0)
 {
  x=str1[i];
  y=str2[i];
  if(x>='a'&&x<='z')
   x-=32;
  if(y>='a'&&y<='z')
   y-=32; 
 }
 d=x-y;
 
 if(d==0)
  printf("Strings are equal");
 else
  printf("Strings are not equal");

 return 0;
}

C program to String Compare - STRCMP

Below is C program to String Compare - STRCMP.

Program:

/* STRING COMPARE - STRCMP */

#include<stdio.h>

int main()
{
 char str1[100], str2[100];
 int i,d=0;
 printf("Please enter first string: ");
 // gets(str1); 
 // fgets is a better option over gets to read multiword string .
 fgets(str1, 100, stdin);
 // Following can be added for extra precaution for '\n' character
 // if(str1[length(str1)-1] == '\n') str1[strlen(str1)-1]=NULL;

 printf("Please enter second string: ");
 // gets(str2); 
 fgets(str2, 100, stdin);
 // if(str2[length(str2)-1] == '\n') str2[strlen(str2)-1]=NULL;

 for(i=0;str1[i]!=NULL&&str2[i]!=NULL;i++)
 {
  if(str1[i]!=str2[i])
   break;
 }
 d=str1[i]-str2[i];
 
 if(d==0)
  printf("Strings are equal");
 else
  printf("Strings are not equal");

 return 0;
}



C program to Toggle case of string

Below is C program to Toggle case of string.

Program:

/* TOGGLE CASE OF STRING */

#include<stdio.h>

int main()
{
 char str[100];
 int i;
 printf("Please enter a string: ");

 // gets(str); 
 // fgets is a better option over gets to read multiword string .

 fgets(str, 100, stdin);
 
 // Following can be added for extra precaution for '\n' character
 // if(str[length(str)-1] == '\n') str[strlen(str)-1]=NULL;

 for(i=0;str[i]!=NULL;i++)
 {
  if(str[i]>='A'&&str[i]<='Z')
   str[i]+=32;
  else if(str[i]>='a'&&str[i]<='z')
   str[i]-=32;
 }
 
 printf("String in toggle case is: %s",str);

 return 0;
}


C program to String to lower case - STRLWR

Below is C program to String to lower case - STRLWR.

Program:

/* STRING TO LOWER CASE - STRLWR */

#include<stdio.h>

int main()
{
 char str[100];
 int i;
 printf("Please enter a string: ");

 // gets(str); 
 // fgets is a better option over gets to read multiword string .

 fgets(str, 100, stdin);

 // Following can be added for extra precaution for '\n' character
 // if(str[length(str)-1] == '\n') str[strlen(str)-1]=NULL;
 
 for(i=0;str[i]!=NULL;i++)
 {
  if(str[i]>='A'&&str[i]<='Z')
   str[i]+=32;
 }
 
 printf("String in lower case is: %s",str);

 return 0;
}
 

C program to String to Upper Case - STRUPR

Below is C program to String to Upper Case - STRUPR.

Program:

/* STRING TO UPPER CASE - STRUPR */
#include<stdio.h>

int main()
{
 char str[100];
 int i;
 printf("Please enter a string: ");

 // gets(str); 
 // fgets is a better option over gets to read multiword string .

 fgets(str, 100, stdin);

 // Following can be added for extra precaution for '\n' character
 // if(str[length(str)-1] == '\n') str[strlen(str)-1]=NULL;
 
 for(i=0;str[i]!=NULL;i++)
 {
  if(str[i]>='a'&&str[i]<='z')
   str[i]-=32;
 }
 
 printf("String in upper case is: %s",str);

 return 0;
}

C program to String Length - STRLEN

Below is C program to String Length - STRLEN.

Program:

/* STRING LENGTH - STRLEN*/
 
#include<stdio.h>

int main()
{
 char str[100];
 int i;
 printf("Please enter a string: ");

 // gets(str); 
 // fgets is a better option over gets to read multiword string .

 fgets(str, 100, stdin);

 // Following can be added for extra precaution for '\n' character
 // if(str[length(str)-1] == '\n') str[strlen(str)-1]=NULL;

 for(i=0;str[i]!=NULL;i++);
 
 printf("Length of string is: %d",i);

 return 0;
}

Woocommerce- Add custom field to “customer details” block in order email


Question: How can we add custom field to “customer details” block in order email?
Answer: Using below code/filter, we can  add custom field to “customer details” block in order email

/**
 * Add custom fields to emails
 */
add_filter('woocommerce_email_customer_details_fields', 'my_checkout_field_order_meta_fields', 40, 3 );
function my_checkout_field_order_meta_fields( $fields, $sent_to_admin, $order ) {
  $fields['custom_field_1'] = array(
    'label' => __( 'Vælg og bekræft din biltype' ),
    'value' => get_post_meta( $order->id, 'Vælg og bekræft din biltype', true ),
  );
  $fields['custom_field_2'] = array(
    'label' => __( 'Afgivet bestilling' ),
    'value' => get_post_meta( $order->id, 'Afgivet bestilling', true ),
  );
 
 
  return $fields;
}

C program to Matrix Multiplication

Below is C program to Matrix Multiplication.

Program:

/* Matrix multiplication */
#include<stdio.h>

int main()
{
 int arr1[3][3],arr2[3][3],arr3[3][3]={0},i,j,k;

 printf("Type a matrix of 3 rows & 3 colomns :\n");
 for(i=0;i<3;i++)
  for(j=0;j<3;j++)
   scanf("%d",&arr1[i][j]);
 
 printf("Type another matrix of 3 rows & 3 colomns :\n");
 for(i=0;i<3;i++)
  for(j=0;j<3;j++)
   scanf("%d",&arr2[i][j]);
 
 for(i=0;i<3;i++)
 {
  for(j=0;j<3;j++)
  {
   for(k=0;k<3;k++)
    arr3[i][j]=arr3[i][j]+arr1[i][k]*arr2[k][j];
  }

 }
 
 printf("\n\nOutput:\n");
 for(i=0;i<3;i++)
 {
  for(j=0;j<3;j++)
   printf("%5d",arr3[i][j]);
  printf("\n\n");
 }

 return 0;
}

C program to Matrix Transpose

Below is C program to Matrix Transpose.

Program:

/* Transpose the matrix */
#include<stdio.h>

int main()
{
 int a[4][4],i,j,b;

 for(i=0;i<4;i++)
 {
  printf("\nEnter elements of %d row of Matrix: ",i+1);
  for(j=0;j<4;j++)
   scanf("%d",&a[i][j]);
 }
 
 for(i=0;i<4;i++)
 {
  for(j=i+1;j<4;j++)
  {
   b=a[i][j];
   a[i][j]=a[j][i];
   a[j][i]=b;
  }
 }

 printf("\nTransposed Matrix:\n\n");
 for(i=0;i<4;i++)
 {
  for(j=0;j<4;j++)
   printf("%4d",a[i][j]);
  printf("\n");
 }
 return 0;
}

C program to Sum of two Matrix

Below is C program to Sum of two Matrix.

Program:

/* Sum of two Matrix */
#include<stdio.h>

int main()
{
  int a[5][5],b[5][5],c[5][5];
  int i,j;

  for(i=0;i<5;i++)
  {
    printf("\nEnter elements of %d row of first Matrix: ",i+1);
    for(j=0;j<5;j++)
      scanf("%d",&a[i][j]);
  }
  
  for(i=0;i<5;i++)
  {
    printf("\nEnter elements of %d row of 2nd Matrix: ",i+1);
    for(j=0;j<5;j++)
      scanf("%d",&b[i][j]);
  }
  
  printf("\nSum of Matrix:\n\n");
  for(i=0;i<5;i++)
  {
    for(j=0;j<5;j++)
    {
      c[i][j]=a[i][j]+b[i][j];
      printf("%3d ",c[i][j]);
    }
    printf("\n");
  }
  return 0;
}

C program to Insertion Sort

Below is C program to Insertion Sort.

Program:

/* Insertion Sort */
#include<stdio.h>

int main()
{
 int arr[10],i,j,new;
 printf("Please enter 10 values:\n");
 for(i=0;i<10;i++)
  scanf("%d",&arr[i]);
 
 for(i=1;i<10;i++)
 {
  new=a[i];
  for(j=i-1;j >=0&&new < a[j];j--)
  {
   a[j+1]=a[j];
  }
  a[j+1]=new;
 }
  
 printf("Sorted Array is:\n");
 for(i=0;i<10;i++)
  printf("%d\n",arr[i]);
 
 return 0;
}

C program to Selection Sort

Below is C program to Selection Sort.

Program:

/* Selection Sort */
#include<stdio.h>

int main()
{
 int arr[10],i,j,k,t;
 printf("Please enter 10 values:\n");
 for(i=0;i<10;i++)
  scanf("%d",&arr[i]);
 
 for(i=0;i<10;i++)
 {
  k=i;
  for(j=i;j<10;j++)
  {
   if(a[k]>a[j])
    k=j;
  }
  if(k!=i)
  {
   t=a[k];
   a[k]=a[i];
   a[i]=t;
  }
 }
 
 printf("Sorted Array is:\n");
 for(i=0;i<10;i++)
  printf("%d\n",arr[i]);
 
 return 0;
}

C program to Bubble Sort

Below is C program to Bubble Sort.

Program:

/* Bubble Sort */
#include<stdio.h>

int main()
{
 int arr[10],i,j,t;
 printf("Please enter 10 values:\n");
 for(i=0;i<10;i++)
  scanf("%d",&arr[i]);
 
 for(i=0;i<9;i++)
 {
  for(j=0;j<9-i;j++)
  {
   if (arr[j]>arr[j+1])
   {
    t=arr[j];
    arr[j]=arr[j+1];
    arr[j+1]=t;
   }
  }
 }
 
 printf("Sorted Array is:\n");
 for(i=0;i<10;i++)
  printf("%d\n",arr[i]);
 
 return 0;
}