Showing posts with label golden programming rules. Show all posts
Showing posts with label golden programming rules. Show all posts

Thursday, March 29, 2018

How To Responsively Rearrange DIV Elements With CSS?

Here is a small, but useful trick that can help you. when you want to change order of elements on the page on mobile devices. Of course, it may be used for any other purposes.

First of all, you have to specify a container:
<div class="row order_container">
</div>

Secondly, define inner elements with appropriate classes:
<div class="row order_container">
 <div class="col-md-6">DIV #1</div>
 <div class="col-md-6">DIV #2<>
</div>
As you can see the default order is following: DIV #1 and then DIV #2 But how can we change this order on mobile devices? It's simple. Add for each element class for order and define its as following:
<style>
@media screen and (max-width: 786px) {
 .order_container { display: flex; flex-flow: column; }
 .order4 { order: 4; }
 .order3 { order: 3; }
 .order2 { order: 2; }
 .order1 { order: 1; }
}
</style>

<div class="row order_container">
 <div class="col-md-6 order2">DIV #1</div>
 <div class="col-md-6 order1">DIV #2<>
</div>
Now in mobile the order of elements will be following: DIV #2 and then DIV #1

Saturday, November 28, 2015

Is it always necessary to use "is_array()" before a foreach?

Many times I see a code, that fails because of one simple and very common programmer mistake.
Programmers often use variabled in foreach() construction without validation before.

This mistake may leads to unstable work of your code.
It must be a "golden" rule of every PHP programmer to always use a validation of  variable before running foreach() construction.

You may do it in few ways:

1. Direct validation:
if(is_array($users))   {
    foreach($users as $user){

    }
} 


2. Casting (not recommended, you know why, right?):
foreach((array)$users as $user){

} 

such way is better, but still...:
$users = (array)$users;
foreach($users as $user){

} 


3. Your own function for handling such cases:
function actionHandelingUsers($users)
{
    if(!is_array($users))
    {
        throw new Exception('$users must be an array');
    }

    foreach($users as $user){
        ...
    }
}

Ok, but sometimes I hear a following argument: my function is always returns an array, why do I need to perform a validation?

The answer is simple: there is no always in programming - what if I decide to change yuor function output? What will be with yuor code after the function will return TRUE instead of array()? You know, right - your code will crash...

The same answer about  using of empty() instead of is_array(): empty() doesn't check if the value is array... , so you may not use it in this case.