Tag Archives: Connect Application

Challenging CSS Best Practices

When it comes to CSS, I believe that the sacred principle of “separation of concerns” (SoC) has lead us to accept bloat, obsolescence, redundancy, poor caching and more. Now, I’m convinced that the only way to improve how we author style sheets is by moving away from this principle.

For those of you who have never heard of the SoC principle in the context of Web design, it relates to something commonly known as the “separation of the three layers”:

  • structure,
  • presentation,
  • behavior.

It is about dividing these concerns into separate resources: an HTML document, one or more cascading style sheets and one or more JavaScript files.

But when it comes to the presentational layer, “best practice” goes way beyond the separation of resources. CSS authors thrive on styling documents entirely through style sheets, an approach that has been sanctified by Dave Shea’s excellent project CSS Zen Garden. CSS Zen Garden is what most — if not all — developers consider to be thestandard for how to author style sheets.

The Standard

To help me illustrate issues related to today’s best practices, I’ll use a very common pattern: the media object. Its combination of markup and CSS will be our starting point.

MARKUP

In our markup, a wrapper (div.media) contains an image wrapped in a link (a.img), followed by a div (div.bd):

<div>
  <a href="http://twitter.com/thierrykoblentz">
        <img src="thierry.jpg" alt="me" width="40" />
  </a>
  <div>
    @thierrykoblentz 14 minutes ago
  </div>
</div>

CSS

Let’s give a 10-pixel margin to the wrapper and style both the wrapper and div.bd asblock-formatting contexts (BFC). In other words, the wrapper will contain the floated link, and the content of div.bd will not wrap around said link. A gutter between the image and text is created with a 10-pixel margin (on the float):

.media {
    margin: 10px;
}
.media,
.bd {
    overflow: hidden;
    _overflow: visible;
    zoom: 1;
}
.media .img {
    float: left;
    margin-right: 10px;
}
.media .img img {
    display: block;
}

RESULT

Here is the presentation of the wrapper, with the image in the link and the blob of text:


me
 

@thierrykoblentz 14 minutes ago

 

A NEW REQUIREMENT COMES IN

Suppose we now need to be able to display the image on the other side of the text as well.

MARKUP

Thanks to the magic of BFC, all we need to do is change the styles of the link. For this, we use a new class, imgExt.

<div>
    <a href="http://twitter.com/thierrykoblentz">
        <img src="thierry.jpg" alt="me" width="40" />
  </a>
  <div>
    @thierrykoblentz 14 minutes ago
  </div>
</div>

CSS

We’ll add an extra rule to float the link to the right and change its margin:

.media {
    margin: 10px;
}
.media,
.bd {
    overflow: hidden;
    _overflow: visible;
    zoom: 1;
}
.media .img {
    float: left;
    margin-right: 10px;
}
.media .img img {
    display: block;
}
.media .imgExt {
    float: right;
    margin-left: 10px;
}

RESULT

The image is now displayed on the opposite side:


me
 

@thierrykoblentz 14 minutes ago

 

ONE MORE REQUIREMENT COMES IN

Suppose we now need to make the text smaller when this module is inside the right rail of the page. To do that, we create a new rule, using #rightRail as a contextual selector:

MARKUP

Our module is now inside a div#rightRail container:

<div id="rightRail">
    <div>
        <a href="http://twitter.com/thierrykoblentz">
            <img src="thierry.jpg" alt="me" width="40" />
        </a>
        <div>
            @thierrykoblentz 14 minutes ago
        </div>
    </div>
</div>

CSS

Again, we create an extra rule, this time using a descendant selector, #rightRail .bd.

.media {
    margin: 10px;
}
.media,
.bd {
    overflow: hidden;
    _overflow: visible;
    zoom: 1;
}
.media .img {
    float: left;
    margin-right: 10px;
}
.media .img img {
    display: block;
}
.media .imgExt {
    float: right;
    margin-left: 10px;
}
#rightRail .bd {
    font-size: smaller;
}

RESULT

Here is our original module, showing inside div#rightRail:


me
 

@thierrykoblentz 14 minutes ago

 

 

What’s Wrong With This Model?

  • Simple changes to the style of our module have resulted in new rules in the style sheet.
    There must be a way to style things without always having to write more CSS rules.
  • We are grouping selectors for common styles (.media,.bd {}).
    Grouping selectors, rather than using a class associated with these styles, will lead to more CSS.
  • Of our six rules, four are context-based.
    Rules that are context-specific are hard to maintain. Styles related to such rules are not very reusable.
  • RTL and LTR interfaces become complicated.
    To change direction, we’d need to overwrite some of our styles (i.e. write morerules). For example:
.rtl .media .img {
    margin-right: auto; /* reset */
    float: right;
    margin-left: 10px;
}
.rtl .media .imgExt {
    margin-left: auto; /* reset */
    float: left;
    margin-right: 10px;
}

 

Meet Atomic Cascading Style Sheet

a·tom·ic
/ə’tämik/
of or forming a single irreducible unit or component in a larger system.

As we all know, the smaller the unit, the more reusable it is.

“Treat code like Lego. Break code into the smallest little blocks possible.” —@csswizardry (via @stubbornella#btconf

— Smashing Magazine (@smashingmag) May 27, 2013

To break down styles into irreducible units, we can map classes to a single style, rather than many. This will result in a more granular palette of rules, which in turn improves reusability.

Let’s revisit the media object using this new approach.

MARKUP

We are using five classes, none of which are related to content:

<div>
    <a href="http://twitter.com/thierrykoblentz">
        <img src="thierry.jpg" alt="me" width="40" />
    </a>
    <div>
        @thierrykoblentz 14 minutes ago
    </div>
</div>

CSS

Each class is associated with one particular style. For the most part, this means we have one declaration per rule.

.Bfc {
    overflow: hidden;
    zoom: 1;
}
.M-10 {
    margin: 10px;
}
.Fl-start {
    float: left;
}
.Mend-10 {
    margin-right: 10px;
}
.Fz-s {
    font-size: smaller;
}

RESULT


me
 

@thierrykoblentz 14 minutes ago

 

WHAT IS THIS ABOUT?

Let’s ignore the class names for now and focus on what this does (or does not):

  • No contextual styling
    We do not use contextual or descendant selectors, which means that our style sheet has no dead weight.
  • Directions (left and right) are “abstracted.”
    Rather than overwriting styles, we serve a RTL style sheet that contains rules such as these:
.Fl-start {
    float: right;
}
.Mend-10 {
    margin-left: 10px;
}

Same classes, same properties, different values.

But the most important thing to notice here is that we are styling via markup. We have changed the context in which we style our modules. We are now editing HTML templates instead of style sheets.

I believe that this approach is a game-changer because it narrows the scope dramatically. We are styling not in the global scope (the style sheet), but at the module and block level. We can change the style of a module without worrying about breaking something else on the page. And we can do this without adding any rule to the style sheet, let alone creating a new class and rule:

.someBasicStyleForThisElementHere {...}

We get no redundancy. Selectors are not duplicated, and styles belong to a single rule instead of being part of many. For example, the style sheets that this page links to contain 72 float declarations.

Also, abandoning a style — for example, deciding to always keep the image on the left side of the module — does not make any of our rules obsolete.

SOUND GOOD?

Not sold yet? I hear you saying, “This goes against every single rule in the book. This is no better than inline styling. And your class names are not only cryptic, but unsemantic, too!”

Fair enough. Let’s address these concerns.

REGARDING UNSEMANTIC CLASS NAMES

If you check the W3C’s “Tips for Webmasters,” where it says “Good names don’t change,” you’ll see that the argument is about maintenance, not semantics per se. All it says is that changing styles is easier in a CSS file than in multiple HTML files. .border4pxwould be a bad name only if changing the style of an element required us to change the declaration that that class name is associated with. In other words:

.border4px {border-width:2px;}

REGARDING CRYPTIC CLASS NAMES

For the most part, these class names follow the syntax of Zen Coding — see the “Zen Coding Cheat Sheet” (PDF) — now renamed Emmet. In other words, they are simple abbreviations.

There are exceptions for styles associated with direction (left and right) and styles that involve a combination of declarations. For example, Bfc stands for “block-formatting context.”

REGARDING MIMICKING INLINE STYLES

Hopefully, the diagram below clears things up:

Venn diagram that shows all possible logical relations between inline styles and styling via classes and markup.
Inline styles versus Atomic CSS.

  • Specificity
    The technique is not as specific as @style. It lowers style weight because rules rely on a single class, as opposed to rules like .parent .bd {}, which clocks in at 0.0.2.0 (see “CSS Specificity: Things You Should Know”).
  • Verbosity
    Most classes are abbreviations of declarations (for example, M-10 versus margin: 10px). Some classes, such as Bfc, refer to more than one style (see “Mapping” in the diagram above). Other classes use “start” and “end” keywords, rather than left and right values (see “Abstraction” in the diagram above).

Here are the advantages of @style:

  • Scope
    Styles are “sandboxed” to the nodes they are attached to.
  • Portability
    Because the styles are “encapsulated,” you can move modules around without losing their styles. Of course, we still need the style sheet; however, because we are making context irrelevant, modules can live anywhere on a page, website or even network.

The Path To Bloat

Because the styles of our module are tied only to presentational class names, they can be anything we want them to be. For example, if we need to create a simple two-column layout, all we need to do is replace the link with a div in our template. That would look like this:

<div>
    <div>
        column 1
    </div>
    <div>
        column 2
    </div>
</div>

And we would need only one extra rule in the style sheet:

.Bfc {
    overflow: hidden;
    zoom: 1;
}
.M-10 {
    margin: 10px;
}
.Fl-start {
    float: left;
}
.Mend-10 {
    margin-right: 10px;
}
.Fz-s {
    font-size: smaller;
}
.W-50 {
    width: 50%;
}

Compare this to the traditional way:

<div>
    <div>
        column 1
    </div>
    <div>
        sidebar
    </div>
</div>

This would require us to create three new classes, to add an extra rule and to group selectors.

.wrapper,
.content,
.media,
.bd {
    overflow: hidden;
    _overflow: visible;
    zoom: 1;
}
.sidebar {
    width: 50%;
}
.sidebar,
.media .img {
    float: left;
    margin-right: 10px;
}
.media .img img {
    display: block;
}

I think the code above pretty well demonstrates the price we pay for following the SoC principle. In my experience, all it does is grow style sheets.

Moreover, the larger the files, the more complex the rules and selectors become. And then no one would dare edit the existing rules:

  • We leave alone rules that we suspect to be obsolete for fear of breaking something.
  • We create new rules, rather than modify existing ones, because we are not sure the latter is 100% safe.

In other words, we make things worse because we can get away with bloat.

Nowadays, people are accustomed to very large style sheets, and many authors think they come with the territory. Rather than fighting bloat, they use tools (i.e. preprocessors) to help them deal with it. Chris Eppstein tells us:

“LinkedIn has over 1,100 Sass files (230k lines of SCSS) and over 90 web developers writing Sass every day.”

CSS BLOAT VS. HTML BLOAT

Let’s face it: the data has to live somewhere. Consider these two blocks:

<div>
<div>

In many cases, the “semantic” class name makes up more bytes than the presentational class name (.wrapper versus .Bfc). But I do not think this is a real concern compared to what most apps onboard these days via data- attributes.

This is where gzip comes into play, because the high redundancy in class names across a document would achieve better compression. And the same is true of style sheets, in which we have many redundant sequences:

.M-1 {margin: 1px;}
.M-2 {margin: 2px;}
.M-4 {margin: 4px;}
.M-6 {margin: 6px;}
.M-8 {margin: 8px;}
etc.

Caching

Presentational rules do not change. Style sheets made from such rules mature into tool sets in which authors can find everything they need. By their nature, they stop growing and become immutable, and immutable is cache-friendly.

No More .button Class?

The technique I’m discussing here is not about banning “semantic” class names or rules that group many declarations. The idea is to reevaluate the benefits of the common approach, rather than adopting it as the de facto technique for styling Web pages. In other words, we are restricting the “component” approach to the few cases in which it makes the most sense.

For example, you may find the following rules in our style sheets, rules that set styles for which we do not create simple classes or rules that ensure cross-browser support.

.button {
    display: inline-block;
    *display: inline;
    zoom: 1;
    font-size: bold 16px/2em Arial;
   	height: 2em;
   	box-shadow: inset 1px 1px 2px 0px #fff;
   	background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #ededed), color-stop(1, #dfdfdf));
   	background: linear-gradient(center top, #ededed 5%, #dfdfdf 100%);
   	filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ededed', endColorstr='#dfdfdf');
   	background-color: #ededed;
    color: #777;
    text-decoration: none;
   	text-align: center;
   	text-shadow: 1px 1px 2px #ffffff;
   	border-radius: 4px;
   	border: 2px solid #dcdcdc;
}
.modal {
    position: fixed;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
    *width: 600px;
    *margin-left: -300px;
    *top: 50px;
}
@media screen {
    .modal {
        width: 600px;
        margin-left: -300px;
        top: 50px;
    }
}

On the other hand, you would not see rules like the ones below (i.e. styles bound to particular modules), because we prefer to apply these same styles using multiple classes: one for font size, one for color, one for floats, etc.

.news-module {
    font-size: 14px;
    color: #555;
    float: left;
    width: 50%;
    padding: 10px;
    margin-right: 10px;
}
.testimonial {
    font-size: 16px;
    font-style: italic;
    color: #222;
    padding: 10px;
}

Do We Include Every Possible Style In Our Style Sheet?

The idea is to have a pool of rules that authors can choose from to style anything they want. Styles that are common enough across a website would become part of the style sheet. If a style is too specific, then we’d rely on @style (the style attribute). In other words, we’d prefer to pollute the markup rather than the style sheet. The primary goal is to create a sheet made of rules that address various design patterns, from a basic rule that floats an element to “helper” classes.

/**
 * one liner with ellipsis
 * 1. we inherit hyphens:auto from body, which would break "Ell" in table cells
 */
.Ell {
    max-width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-hyphens: none; /* 1 */
    -ms-hyphens: none;
    -o-hyphens: none;
    hyphens: none;
}
/**
 * kinda line-clamp
 * two lines according to default font-size and line-height
 */
.LineClamp {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    font-size: 13px;
    line-height: 1.25;
    max-height: 32px;
    _height: 32px;
    overflow: hidden;
}
/**
 * reveals an hidden element on :hover or :focus
 * visibility can be forced by applying the class "RevealNested-on"
 * IE8+
 */
:root .NestedHidden {
    opacity: 0;
}
:root .NestedHidden:focus,
:root .RevealNested:hover .NestedHidden,
:root .RevealNested-on .NestedHidden {
    opacity: 1;
}

How Does This Scale?

We have just released a brand new My Yahoo, which relies heavily on this technique. This is how it compares to a few other Yahoo products (after gzip’ing):

CSS Assets
answers.yahoo.com 30.1 KB
sports.yahoo.com 67.4 KB
omg.yahoo.com 46.2 KB
yahoo.com 45.9 KB
my.yahoo.com 21.3 KB

Our style sheet weighs 17.9 KB (about 3 KB of which are property-specific), and it is shareable (unlike the style sheets of other properties). The reason for this is that none of the rules it contains relate to content.

Wrapping Up

Because presentational class names have always been deemed “out of bounds,” we — the community — have not really investigated what their use entails. In fact, in the name of best practice, we’ve dismissed every opportunity to explore their potential benefits.

Here at Yahoo, @renatoiwa@StevenRCarlson and I are developing projects with this new CSS architecture. The code appears to be predictable, reusable, maintainable and scalable. These are the results we’ve experienced so far:

  • Less bloat
    We can build entire modules without adding a single line to the style sheets.
  • Faster development
    Styles are driven by classes that are not related to content, so we can copy and paste existing modules to get started.
  • RTL interface for free
    Using start and end keywords makes a lot of sense. It saves us from having to write extra rules for RTL context.
  • Better caching
    A huge chunk of CSS can be shared across products and properties.
  • Very little maintenance (on the CSS side)
    Only a small set of rules are meant to change over time.
  • Less abstraction
    There is no need to look for rules in a style sheet to figure out the styling of a template. It’s all in the markup.
  • Third-party development
    A third party can hand us a template without having to attach a style sheet (or astyle block) to it. No custom rules from third parties means no risk of breakage due to rules that have not been properly namespaced.

(Note that if maintenance is easier on the CSS side than on the HTML side, then the reason is simply that we can cheat on the CSS side by not cleaning up rules. But if we were required to keep things lean and clean, then the pain would be the same.)

FINAL NOTE

I was at a meetup a couple of weeks ago, where I heard Colt McAnlis say, “Tools, not rules.” A quick search for this idiom returned this:

“We all need to be open to new learnings, new approaches, new best practices and we need to be able to share them.”

(al, ea)

/**
* custom styles for this article
* Namespace: “Atomiccss”
*/
.Atomiccss .media {
margin: 10px;
}
.Atomiccss .media,
.Atomiccss .bd {
overflow: hidden;
_overflow: visible;
zoom: 1;
}
.Atomiccss .media .img {
float: left;
margin-right: 10px;
}
.Atomiccss .media .img img {
display: block;
}
.Atomiccss .media .imgExt {
float: right;
margin-left: 10px;
}
.Atomiccss #rightRail .bd {
font-size: smaller;
}
/* ACSS */
.Atomiccss .Bfc {
overflow: hidden;
zoom: 1;
}
.Atomiccss .M-10 {
margin: 10px;
}
.Atomiccss .Fl-start {
float: left;
}
.Atomiccss .Mend-10 {
margin-right: 10px;
}
.Atomiccss .Fz-s {
font-size: smaller;
}
/* for some reason, @width is stripped from the markup */
.Atomiccss img {
width: 40px;
}

PHP Array All Functions

PHP Array Functions

The following list show the different function used in an array.
– array_change_key_case : Changes all keys in an array
– array_chunk : Used to split an array into pieces.
– array_column : Used to return the values from a single column in the input array
– array_combine : Used to creates an array by using one array for keys and another for its values.
– array_count_values : Used to counts all the values of an array.
– array_diff_assoc : Computes the difference of arrays with additional index check
– array_diff_key : Computes the difference of arrays using keys for comparison
– array_diff_uassoc : Computes the difference of arrays with additional index check which is performed by a user supplied callback function
– array_diff_ukey : Computes the difference of arrays using a callback function on the keys for comparison
– array_diff : Computes the difference of arrays
– array_fill_keys : Fill an array with values, specifying keys
– array_fill : Fill an array with values
– array_filter : Filters elements of an array using a callback function
– array_flip : Exchanges all keys with their associated values in an array
– array_intersect_assoc : Computes the intersection of arrays with additional index check
– array_intersect_key : Computes the intersection of arrays using keys for comparison
– array_intersect_uassoc : Computes the intersection of arrays with additional index check, compares indexes by a callback function
– array_intersect_ukey : Computes the intersection of arrays using a callback function on the keysfor comparison
– array_intersect : Computes the intersection of arrays
– array_key_exists : Checks if the given key or index exists in the array
– array_keys : Return all the keys or a subset of the keys of an array
– array_map : Applies the callback to the elements of the given arrays
– array_merge_recursive : Merge two or more arrays recursively
– array_merge : Merge one or more arrays
– array_multisort : Sort multiple or multi-dimensional arrays
– array_pad : Pad array to the specified length with a value
– array_pop : Pop the element off the end of array
– array_product : Calculate the product of values in an array
– array_push : Push one or more elements onto the end of array
– array_rand : Pick one or more random entries out of an array
– array_reduce : Iteratively reduce the array to a single value using a callback function
– array_replace_recursive : Replaces elements from passed arrays into the first array recursively
– array_replace : Replaces elements from passed arrays into the first array
– array_reverse : Return an array with elements in reverse order
– array_search : Searches the array for a given value and returns the corresponding key if successful
– array_shift : Shift an element off the beginning of array
– array_slice : Extract a slice of the array
– array_splice : Remove a portion of the array and replace it with something else
– array_sum : Calculate the sum of values in an array
– array_udiff_assoc : Computes the difference of arrays with additional index check, compares data by a callback function
– array_udiff_uassoc : Computes the difference of arrays with additional index check, compares data and indexes by a callback function
– array_udiff : Computes the difference of arrays by using a callback function for data comparison
– array_uintersect_assoc : Computes the intersection of arrays with additional index check, compares data by a callback function
– array_uintersect_uassoc : Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
– array_uintersect : Computes the intersection of arrays, compares data by a callback function
– array_unique : Removes duplicate values from an array
– array_unshift : Prepend one or more elements to the beginning of an array
– array_values : Return all the values of an array
– array_walk_recursive : Apply a user function recursively to every member of an array
– array_walk : Apply a user function to every member of an array
– array : Create an array
– arsort : Sort an array in reverse order and maintain index association
– asort : Sort an array and maintain index association
– compact : Create array containing variables and their values
– count : Count all elements in an array, or something in an object
– current : Return the current element in an array
– each : Return the current key and value pair from an array and advance the array cursor
– end : Set the internal pointer of an array to its last element
– extract : Import variables into the current symbol table from an array
– in_array : Checks if a value exists in an array
– key_exists : Alias of array_key_exists
– key : Fetch a key from an array
– krsort : Sort an array by key in reverse order
– ksort : Sort an array by key
– list : Assign variables as if they were an array
– natcasesort : Sort an array using a case insensitive “natural order” algorithm
– natsort : Sort an array using a “natural order” algorithm
– next : Advance the internal array pointer of an array
– pos : Alias of current
– prev : Rewind the internal array pointer
– range : Create an array containing a range of elements
– reset : Set the internal pointer of an array to its first element
– rsort : Sort an array in reverse order
– shuffle : Shuffle an array
– sizeof : Alias of count
– sort : Sort an array
– uasort : Sort an array with a user-defined comparison function and maintain index association
– uksort : Sort an array by keys using a user-defined comparison function
– usort : Sort an array by values using a user-defined comparison function

PHP Array Sort Functions

The elements in an array can be either be sort ascending, descending, alphabetical and numerical order. Lets discuss the different sort function used in PHP.

– sort() – used to sort arrays in ascending order.
– rsort() – used to sort arrays in descending order.
– asort() – used to sort associative arrays in ascending order as per values.
– ksort() – used to sort associative arrays in ascending order as per key.
– arsort() – used to sort associative arrays in descending order as per  values.
– krsort() – used to sort associative arrays in descending order  as per key.
– shuffle() – used to randomizes the order of the elements in an array.

Sort arrays in ascending order sort()

<?php
$players = array("Sambir","Rupal","Aadarsh");
sort($players);
print_r($players);
?>

Output:
Array(
[0] => Aadarsh
[1] => Rupal
[2] => Sambir
)

Sort Array in Descending Order – rsort()

<?php
$players = array("Rupal","Sambit","Aadarsh");
rsort($players);
print_r($players);
?>

Output:
Array(
[0] => Sambir
[1] => Rupal
[2] => Aadarsh
)

asort()

<?php
$players = array("Sambir"=>"9","Rupal"=>"10","Aadarsh"=>"8");
asort($players);
print_r($players);
?>

Output:
Array(
[Aadarsh] => 8
[Sambir] => 9
[Rupal] => 10
)

ksort()

<?php
$players = array("Sambir"=>"9","Rupal"=>"10","Aadarsh"=>"8");
ksort($players);
print_r($players);
?>

Output:
Array(
[Aadarsh] => 8
[Rupal] => 10
[Sambir] => 9
)

ksort()

<?php
$players = array("Sambir"=>"9","Rupal"=>"10","Aadarsh"=>"8");
ksort($players);
print_r($players);
?>

Output:
Array(
[Aadarsh] => 8
[Rupal] => 10
[Sambir] => 9
)

arsort()

<?php
$players = array("Sambir"=>"9","Rupal"=>"10","Aadarsh"=>"8");
arsort($players);
print_r($players);
?>

Output:
Array(
[Rupal] => 10
[Sambir] => 9
[Aadarsh] => 8
)

krsort()

<?php
$players = array("Sambir"=>"9","Rupal"=>"10","Aadarsh"=>"8");
krsort($players);
print_r($players);
?>

Output:
Array(
[Sambir] => 9
[Rupal] => 10
[Aadarsh] => 8
)

shuffle()

<?php
$players = array("Sambir","Rupal","Aadarsh");
shuffle($players);
print_r($players);
?>

Output: /* Every time you refresh the value changes. */
Array(
 [0] => Aadarsh
[1] => Sambir
[2] => Rupal
)

PHP Array

Introduction to Array

When creating long, complex programs, it sometimes becomes difficult to access certain elements in a program. for example there is a limitation for using variables in a program: when you declare a variable, you can assign only one value to it. In certain case , you may want to declare hundreds of variables and it may not be possible to remember each and every variable and use it. Array help to accomplish this. An array is a special kind of variable that unlike conventional variables, can storemultiple values that are indexed. To understand this definition let it split it into three parts:.
– An array is a special kind of variable because it is primarily use for strong values.
– Unlike conventional variables, array can store multiple values without any limitation.
– Each value that is assigned to an array is accessed using an index in the form of a number or a string.

Features of Arrays

There are a few underlying features of array that help qualify them as one of the most important elements in any complex program.
– Any number of values can be stored in a single array.
– The value stored in an array can be numeric or string.
– After the value are stored in the array, they can be extracted from it at any given time.
– Arrays enhance the scope and flexibility of a program by allowing data to be accessed easily.
– Array organize complex datastructure that are related in some way.
– It is possible to add values to an array after it is created. which is not possible in case of a variable.
– Values in an array can be retrieved sequentially and randomly.

CREATING A SIMPLE ARRAY

Creating an array is as simple as creating a variable. The only difference is that its main purpose is to hold multiple related values in the same place. consider the fallowing example

<?php
     $week[] = "Sunday";
     $week[] = "Monday";
     $week[] = "Tuesday"; /* And So on */  
?>

Declaring an array by using the array () function

<?php
  $week = array("Sunday", "Monday", "Tuesday","etc..");
?>

ASSOCIATIVE ARRAYS

Arrays that are indexed by using strings are called associative arrays. When you use them, you specified a string instead of number within the square brackets.

<?php
   $student[Name] = "Rishi";
   $student[Age] = "8";
   $student[Game] = "Chess";
?>

OR

<?php
   $student = array(Name=>"Rishi", Age=>"8", Game=>"Chess");
?>

MULTIDIMENSIONAL ARRAYS

As discuss earlier, array can store numbers as well as names. They can also store other arrays. Sucharrays are multidimensional arrays or an array of arrays.

<?php
 $student = array(
 array( Name=>"Rishi", Age=>"8", Game=>"Chess"),
 array( Name=>"Sambit", Age=>"9", Game=>"Chess"),
 array( Name=>"Rupal", Age=>"10", Game=>"Chess"),   
);

echo $student[1][Age];
?>

Output: 9;

Looping through arrays

Another method of accessing the elements in an array and displaying them is by looping. You can use the foreach statement to loop through enumerated, associative and multidimensional arrays.

Looping through an enumerated array

As discuss earlier, the foreach statement comes in handy when looping through an enumerated array. Consider the fallowing example

<?php
foreach ($array as $val){
  echo "My Value=".$val ."<br/>";
}
?>

Looping through an associative array

The foreach statement is also used for looping through an associative arrays, but there is a slight change in the way you use it. You would need to specified the key as well as the value of an element to access a particular element. consider an example

<?php
foreach ($array as $key =>$val){
  echo " $key = $val <br/>";
}
?>

Displaying a multidimensional array

After learning how to loop through enumerated arrays and associative arrays, you might want toknow how to loop through a multidimensional arrays. You can combine your knowledge to looping through enumerated and associative arrays to accomplish this.

<?php
 $student = array(
 array( Name=>"Rishi", Age=>"8", Game=>"Chess"),
 array( Name=>"Sambit", Age=>"9", Game=>"Chess"),
 array( Name=>"Rupal", Age=>"10", Game=>"Chess"),   
);
foreach($student as $st){
 foreach($st as $key => $val){
   echo "$key = $val"."<br/>";
  }
 echo "<hr>";
}
?>

Output:
Name = Rishi
Age = 8
Game = Chess
-------------------------------------
Name = Sambit
Age = 9
Game = Chess
--------------------------------------
Name = Rupal
Age = 10
Game = Chess

PHP Operators

Introducing Operators

In the previous section you learned about variables, data type, and constant and how to declare them. However, to use or declare variables or constants you need operators. The fallowing problem and itssolution explain the use of operators.

Identify the operators to be used

Operators are an integral part of any programming language, they are symbol that represent a specific action. For an example, the plus sign indicates that addition needs to be performed and is an operator use for addition. Using operators, you can perform a number of operation on a variable:
– Assign a value to a variable
– Change the value of a variable
– Compare two or more values
– Specify a condition

There are 6 basic operator categories:

– Arithmetic Operator
– Assignment Operator
– Comparison Operator
– Increment/decrement Operator
– String Operator
– Logical Operator

Arithmetic operators

Arithmetic operators are used to perform elementary mathematical calculation and are used when value of variable declare in integer type.

Name Example Output
Addition $a+$b The sum of $a and $b
Subtraction $a-$b The difference between $a and $b
Multiplication $a*$b The product of $a and $b
Division $a/$b The quotient of $a and $b
Modules $a%$b The remainder after dividing $a and $b

Let us look at some examples for a better understanding of arithmetic operators:

Addition
$a = 3;
$b = 6;
$c = $a+$b ; // The value of $c is now 9.
Subtraction
$a = 11;
$b = 2;
$c = $a-$b; //The value of $c is now 9.
Multiplication
$a = 3;
$b = 3;
$c = $a*$b; //The value of $c is now 9.
Division
$a = 18;
$b = 2;
$c = $a/$b ; //The value of $c is 9.
Modules
$a = 9;
$b = 3;
$c = $a%$b; //The value of $c is now 0.

Assignment Operators

Assignment operators are use to assign a specific value to variable. They are also use to change the existing value of a variable by adding or subtracting from the variable ‘s current value. A few examples are =, +=, -= and .=.
In PHP you can use more than one assignment operator in a single statement, as shown below:

 $a = ($b=4) + ($c=5);

The variable $a, $b and $c are now integer types and will hold the values 9, 4 and 5, respectively.

Operator Usage Output
= (equal to) $a = 9; Assign value 9 to variable $a;
+= (plus equal to) $a += 9; Adds the original value assign to the variable $a to 9. Now the value of $a will be 9.
-= (minus equal to) $a += 3; Subtract the number specified from the original value of $a. Now the value of $a will be 6.
.= (dot equal to) $a .=” new numbers.”; (add) the new value specified with the original value of the variable. Now the value of $a will be 9 new numbers.