|
by via FrontEnd Focus
"Mr Branding" is a blog based on RSS for everything related to website branding and website design, it collects its posts from many sites in order to facilitate the updating to the latest technology.
To suggest any source, please contact me: Taha.baba@consultant.com
|
Sketch 43 recently introduced a rather interesting update to their “.sketch” file format, making it more human-readable when opened in a code editor (by that I mean we actually could read the coding of the .sketch file and see details of the layers and styles in code format).
“Huh? What? Why would you want to do that?”
Well, you wouldn’t — this new file format is designed to be read by web browsers so that we can build apps that interpret .sketch files (think: better design handoff, Git-like version control, maybe even Sketch → HTML/CSS automation).
Prior to version 43, the .sketch file format was written in binary (you don’t need to know what that means, just that it’s unreadable). Now it’s written in JSON, which is not only human-readable but can be read and even parsed by web browsers.
You can witness first-hand how web browsers will read this new file format by reading it yourself. Quite literally, you could dive into the code of a .sketch file, edit the JSON code itself, then open the .sketch file in Sketch and see the changes made to our design (don’t worry, designers are still expected to design using the Sketch GUI, this update doesn’t change that).
Here’s how it’s done.
Continue reading %Why You Need to Know About Sketch’s New File Format%
In this tutorial, I am going to make a list of common PHP array functions with examples of usage and best practices. Every PHP developer must know how to use them and how to combine array functions to make code readable and short.
Also, there is a presentation with given code examples, so you can download it from the related links and show it to your colleagues to build a stronger team.
Let's start with the basic functions that work with array keys and values. One of them is array_combine(), which creates an array using one array for keys and another for its values:
$keys = ['sky', 'grass', 'orange']; $values = ['blue', 'green', 'orange']; $array = array_combine($keys, $values); print_r($array); // Array // ( // [sky] => blue // [grass] => green // [orange] => orange // )
You should know, that the function array_values() returns an indexed array of values, array_keys() returns an array of keys of a given array, and array_flip() exchanges keys with values:
print_r(array_keys($array)); // ['sky', 'grass', 'orange'] print_r(array_values($array)); // ['blue', 'green', 'orange'] print_r(array_flip($array)); // Array // ( // [blue] => sky // [green] => grass // [orange] => orange // )
The function list(), which is not really a function, but a language construction, is designed to assign variables in a short way. For example, here is a basic example of using the list() function:
// define array $array = ['a', 'b', 'c']; // without list() $a = $array[0]; $b = $array[1]; $c = $array[2]; // with list() list($a, $b, $c) = $array;
This construction works perfectly with functions like preg_slit() or explode() . Also, you can skip some parameters, if you don't need them to be defined:
$string = 'hello|wild|world';
list($hello, , $world) = explode('|', $string);
echo("$hello, $world"); // hello, world
Also, list() can be used with foreach, which makes this construction even better:
$arrays = [[1, 2], [3, 4], [5, 6]];
foreach ($arrays as list($a, $b)) {
$c = $a + $b;
echo($c . ', '); // 3, 7, 11,
}
With the extract() function, you can export an associative array to variables. For every element of an array, a variable will be created with the name of a key and value as a value of the element:
$array = [
'clothes' => 't-shirt',
'size' => 'medium',
'color' => 'blue',
];
extract($array);
echo("$clothes $size $color"); // t-shirt medium blue
Be aware that extract() is not safe if you are working with user data (like results of requests), so it is better to use this function with the flags EXTR_IF_EXISTS and EXTR_PREFIX_ALL.
The opposite of the previous function is the compact() function, which makes an associative array from variables:
$clothes = 't-shirt';
$size = 'medium';
$color = 'blue';
$array = compact('clothes', 'size', 'color');
print_r($array);
// Array
// (
// [clothes] => t-shirt
// [size] => medium
// [color] => blue
// )
There is a great function for array filtering, and it is called array_filter(). Pass the array as the first param and an anonymous function as the second param. Return true in a callback function if you want to leave this element in the array, and false if you don't:
$numbers = [20, -3, 50, -99, 55];
$positive = array_filter($numbers, function($number) {
return $number > 0;
});
print_r($positive); // [0 => 20, 2 => 50, 4 => 55]
There is a way to filter not only by the values. You can use ARRAY_FILTER_USE_KEY or ARRAY_FILTER_USE_BOTH as a third parameter to pass the key or both value and key to the callback function.
Also, you can call array_filter() without a callback to remove all empty values:
$numbers = [-1, 0, 1]; $not_empty = array_filter($numbers); print_r($not_empty); // [0 => -1, 2 => 1]
You can get only unique values from an array using the array_unique() function. Notice that the function will preserve the keys of the first unique elements:
$array = [1, 1, 1, 1, 2, 2, 2, 3, 4, 5, 5]; $uniques = array_unique($array); print_r($uniques); // Array // ( // [0] => 1 // [4] => 2 // [7] => 3 // [8] => 4 // [9] => 5 // )
With array_column(), you can get a list of column values from a multi-dimensional array, like an answer from a SQL database or an import from a CSV file. Just pass an array and column name:
$array = [
['id' => 1, 'title' => 'tree'],
['id' => 2, 'title' => 'sun'],
['id' => 3, 'title' => 'cloud'],
];
$ids = array_column($array, 'id');
print_r($ids); // [1, 2, 3]
Starting from PHP 7, array_column() becomes even more powerful, because it is now allowed to work with an array of objects. So working with an array of models just became easier:
$cinemas = Cinema::find()->all(); $cinema_ids = array_column($cinemas, 'id'); // php7 forever!
Using array_map(), you can apply a callback to every element of an array. You can pass a function name or anonymous function to get a new array based on the given array:
$cities = ['Berlin', 'KYIV', 'Amsterdam', 'Riga'];
$aliases = array_map('strtolower', $cities);
print_r($aliases); // ['berlin', 'kyiv, 'warsaw', 'riga']
$numbers = [1, -2, 3, -4, 5];
$squares = array_map(function($number) {
return $number ** 2;
}, $numbers);
print_r($squares); // [1, 4, 9, 16, 25]
There is a myth that there is no way to pass values and keys of an array to a callback, but we can bust it:
$model = ['id' => 7, 'name'=>'James'];
$callback = function($key, $value) {
return "$key is $value";
};
$res = array_map($callback, array_keys($model), $model);
print_r($res);
// Array
// (
// [0] => id is 7
// [1] => name is James
// )
But this looks dirty. It is better to use array_walk() instead. This function looks the same as array_map(), but it works differently. First of all, an array is passed by a reference, so array_walk() doesn't create a new array, but changes a given array. So as a source array, you can pass the array value by a reference in a callback. Array keys can also be passed easily:
$fruits = [
'banana' => 'yellow',
'apple' => 'green',
'orange' => 'orange',
];
array_walk($fruits, function(&$value, $key) {
$value = "$key is $value";
});
print_r($fruits);
// Array
// (
// [banana] => banana is yellow
// [apple] => apple is green
// [orange] => orange is orange
// )
The best way to merge two or more arrays in PHP is to use the array_merge() function. Items of arrays will be merged together, and values with the same string keys will be overwritten with the last value:
$array1 = ['a' => 'a', 'b' => 'b', 'c' => 'c']; $array2 = ['a' => 'A', 'b' => 'B', 'D' => 'D']; $merge = array_merge($array1, $array2); print_r($merge); // Array // ( // [a] => A // [b] => B // [c] => c // [D] => D // )
To remove array values from another array (or arrays), use array_diff(). To get values which are present in given arrays, use array_intersect(). The next examples will show how it works:
$array1 = [1, 2, 3, 4]; $array2 = [3, 4, 5, 6]; $diff = array_diff($array1, $array2); print_r($diff); // [0 => 1, 1 => 2] $intersect = array_intersect($array1, $array2); print_r($intersect); // [2 => 3, 3 => 4]
Use array_sum() to get a sum of array values, array_product() to multiply them, or create your own formula with array_reduce():
$numbers = [1, 2, 3, 4, 5];
echo(array_sum($numbers)); // 15
echo(array_product($numbers)); // 120
echo(array_reduce($numbers, function($carry, $item) {
return $carry ? $carry / $item : 1;
})); // 0.0083 = 1/2/3/4/5
To count all the values of an array, use array_count_values(). It will give all unique values of a given array as keys and a count of these values as a value:
$things = ['apple', 'apple', 'banana', 'tree', 'tree', 'tree']; $values = array_count_values($things); print_r($values); // Array // ( // [apple] => 2 // [banana] => 1 // [tree] => 3 // )
To generate an array with a given size and the same value, use array_fill():
$bind = array_fill(0, 5, '?'); print_r($bind); // ['?', '?', '?', '?', '?']
To generate an array with a range in of keys and values, like day hours or letters, use range():
$letters = range('a', 'z');
print_r($letters); // ['a', 'b', ..., 'z']
$hours = range(0, 23);
print_r($hours); // [0, 1, 2, ..., 23]
To get a part of an array—for example, just the first three elements—use array_slice():
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; $top = array_slice($numbers, 0, 3); print_r($top); // [1, 2, 3]
It is good to remember that every sorting function in PHP works with arrays by a reference and returns true on success or false on failure. There's a basic sorting function called sort(), and it sorts values in ascending order without preserving keys. The sorting function can be prepended by the following letters:
You can see the combinations of these letters in the following table:
| a | k | r | u | |
| a | asort | arsort | uasort | |
| k | ksort | krsort | ||
| r | arsort | krsort | rsort | |
| u | uasort | usort |
The real magic begins when you start to combine array functions. Here is how you can trim and remove empty values in just a single line of code with array_filter() and array_map():
$values = ['say ', ' bye', ' ', ' to', ' spaces ', ' '];
$words = array_filter(array_map('trim', $values));
print_r($words); // ['say', 'bye', 'to', 'spaces']
To create an id to a title map from an array of models, we can use a combination of array_combine() and array_column():
$models = [$model1, $model2, $model3];
$id_to_title = array_combine(
array_column($models, 'id'),
array_column($models, 'title')
);
To get the top three values of an array, we can use array_count_values(), arsort(), and array_slice():
$letters = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'd', 'd', 'd', 'd']; $values = array_count_values($letters); // get key to count array arsort($values); // sort descending preserving key $top = array_slice($values, 0, 3); // get top 3 print_r($top); // Array // ( // [d] => 5 // [a] => 4 // [b] => 2 // )
It is easy to use array_sum() and array_map() to calculate the sum of order in a few rows:
$order = [
['product_id' => 1, 'price' => 99, 'count' => 1],
['product_id' => 2, 'price' => 50, 'count' => 2],
['product_id' => 2, 'price' => 17, 'count' => 3],
];
$sum = array_sum(array_map(function($product_row) {
return $product_row['price'] * $product_row['count'];
}, $order));
print_r($sum); // 250
As you can see, knowledge of the main array functions can make your code much shorter and more readable. Of course, PHP has many more array functions, and even the given functions have many variations to use with extra parameters and flags, but I think that in this tutorial we've covered the basics that every PHP developer should know.
Please note that I've created a presentation with the given examples, so you can download it from the related links and show it to your team.
If you have any questions, don't hesitate to ask them in the comments to the article.
In the first introductory Chart.js tutorial of the series, you learned how to install and use Chart.js in a project. You also learned about some global configuration options that can be used to change the fonts and tooltips of different charts. In this tutorial, you will learn how to create line and bar charts in Chart.js.
Line charts are useful when you want to show the changes in value of a given variable with respect to the changes in some other variable. The other variable is usually time. For example, line charts can be used to show the speed of a vehicle during specific time intervals.
Chart.js allows you to create line charts by setting the type key to line. Here is an example:
var lineChart = new Chart(speedCanvas, {
type: 'line',
data: speedData,
options: chartOptions
});
We will now be providing the data as well as the configuration options that we need to plot the line chart.
var speedData = {
labels: ["0s", "10s", "20s", "30s", "40s", "50s", "60s"],
datasets: [{
label: "Car Speed",
data: [0, 59, 75, 20, 20, 55, 40],
}]
};
var chartOptions = {
legend: {
display: true,
position: 'top',
labels: {
boxWidth: 80,
fontColor: 'black'
}
}
};
Since we have not provided any color for the line chart, the default color rgba(0,0,0,0.1) will be used. We have not made any changes to the tooltip or the legend. You can read more about changing the crate size, the tooltip or the legend in the first part of the series.
In this part, we will be focusing on different options specifically available for modifying line charts. All the options and data that we provided above will create the following chart.
The color of the area under the curve is determined by the backgroundColor key. All the line charts drawn using this method will be filled with the given color. You can set the value of the fill key to false if you only want to draw a line and not fill it with any color.
One more thing that you might have noticed is that we are using discrete data points to plot the chart. The library automatically interpolates the values of all other points by using built-in algorithms.
By default, the points are plotted using a custom weighted cubic interpolation. However, you can also set the value of the cubicInterpolationMode key to monotone to plot points more accurately when the chart you are plotting is defined by the equation y = f(x). The tension of the plotted Bezier curve is determined by the lineTension key. You can set its value to zero to draw straight lines. Please note that this key is ignored when the value of cubicInterpolationMode has already been specified.
You can also set the value of the border color and its width using the borderColor and borderWidth keys. If you want to plot the chart using a dashed line instead of a solid line, you can use the borderDash key. It accepts an array as its value whose elements determine the length and spacing of the dashes respectively.
The appearance of the plotted points can be controlled using the pointBorderColor, pointBackgroundColor, pointBorderWidth, pointRadius, and pointHoverRadius properties. There is also a pointHitRadius key, which determines the distance at which the plotted points will start interacting with the mouse.
var speedData = {
labels: ["0s", "10s", "20s", "30s", "40s", "50s", "60s"],
datasets: [{
label: "Car Speed",
data: [0, 59, 75, 20, 20, 55, 40],
lineTension: 0,
fill: false,
borderColor: 'orange',
backgroundColor: 'transparent',
borderDash: [5, 5],
pointBorderColor: 'orange',
pointBackgroundColor: 'rgba(255,150,0,0.5)',
pointRadius: 5,
pointHoverRadius: 10,
pointHitRadius: 30,
pointBorderWidth: 2,
pointStyle: 'rectRounded'
}]
};
The above speedData object plots the same data points as the previous chart but with custom values set for all of the properties.
You can also plot multiple lines on a single chart and provide different options to draw each of them like this:
var dataFirst = {
label: "Car A - Speed (mph)",
data: [0, 59, 75, 20, 20, 55, 40],
lineTension: 0.3,
// Set More Options
};
var dataSecond = {
label: "Car B - Speed (mph)",
data: [20, 15, 60, 60, 65, 30, 70],
// Set More Options
};
var speedData = {
labels: ["0s", "10s", "20s", "30s", "40s", "50s", "60s"],
datasets: [dataFirst, dataSecond]
};
var lineChart = new Chart(speedCanvas, {
type: 'line',
data: speedData
});
Bar charts are useful when you want to compare a single metric for different entities—for example, the number of cars sold by different companies or the number of people in certain age groups in a town. You can create bar charts in Chart.js by setting the type key to bar. By default, this will create charts with vertical bars. If you want to create charts with horizontal bars, you will have to set the type to horizontalBar.
var barChart = new Chart(densityCanvas, {
type: 'bar',
data: densityData,
options: chartOptions
});
Let's create a bar chart which plots the density of all the planets in our solar system. The density data has been taken from the Planetary Fact Sheet provided by NASA.
var densityData = {
label: 'Density of Planets (kg/m3)',
data: [5427, 5243, 5514, 3933, 1326, 687, 1271, 1638]
};
var barChart = new Chart(densityCanvas, {
type: 'bar',
data: {
labels: ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"],
datasets: [densityData]
}
});
The parameters provided above will create the following chart:
Just like the line chart, the bars are filled with a light gray color this time as well. You can change the color of the bars using the backgroundColor key. Similarly, the color and width of the borders of different bars can be specified using the borderColor and borderWidth keys.
If you want the library to skip drawing the border for a particular edge, you can specify that edge as a value of the borderSkipped key. You can set its value to top, left, bottom, or right. You can also change the border and background color of different bars when they are hovered using the hoverBorderColor and hoverBackgroundColor key.
The bars in the bar chart above were sized automatically. However, you can control the width of individual bars using the barThickness and barPercentage properties. The barThickness key is used to set the thickness of bars in pixels, and barPercentage is used to set the thickness as a percentage of the available category width.
You can also show or hide a particular axis using its display key. Setting the value of display to false will hide that particular axis. You can read more about all these options on the documentation page.
Let's make the density chart more interesting by overriding the default values for bar charts using the following code.
var densityData = {
label: 'Density of Planets (kg/m3)',
data: [5427, 5243, 5514, 3933, 1326, 687, 1271, 1638],
backgroundColor: [
'rgba(0, 99, 132, 0.6)',
'rgba(30, 99, 132, 0.6)',
'rgba(60, 99, 132, 0.6)',
'rgba(90, 99, 132, 0.6)',
'rgba(120, 99, 132, 0.6)',
'rgba(150, 99, 132, 0.6)',
'rgba(180, 99, 132, 0.6)',
'rgba(210, 99, 132, 0.6)',
'rgba(240, 99, 132, 0.6)'
],
borderColor: [
'rgba(0, 99, 132, 1)',
'rgba(30, 99, 132, 1)',
'rgba(60, 99, 132, 1)',
'rgba(90, 99, 132, 1)',
'rgba(120, 99, 132, 1)',
'rgba(150, 99, 132, 1)',
'rgba(180, 99, 132, 1)',
'rgba(210, 99, 132, 1)',
'rgba(240, 99, 132, 1)'
],
borderWidth: 2,
hoverBorderWidth: 0
};
var chartOptions = {
scales: {
yAxes: [{
barPercentage: 0.5
}]
},
elements: {
rectangle: {
borderSkipped: 'left',
}
}
};
var barChart = new Chart(densityCanvas, {
type: 'horizontalBar',
data: {
labels: ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"],
datasets: [densityData],
},
options: chartOptions
});
The densityData object is used to set the border and background color of the bars. There are two things worth noticing in the above code. First, the values of the barPercentage and borderSkipped properties have been set inside the chartOptions object instead of the dataDensity object.
Second, the chart type has been set to horizontalBar this time. This also means that you will have to change the value of barThickness and barPercentage for the y-axis instead of the x-axis for them to have any effect on the bars.
The parameters provided above will create the following bar chart.
You can also plot multiple datasets on the same chart by assigning an id of the corresponding axis to a particular dataset. The xAxisID key is used to assign the id of any x-axis to your dataset. Similarly, the yAxisID key is used to assign the id of any y-axis to your dataset. Both the axes also have an id key that you can use to assign unique ids to them.
If the last paragraph was a bit confusing, the following example will help clear things up.
var densityData = {
label: 'Density of Planet (kg/m3)',
data: [5427, 5243, 5514, 3933, 1326, 687, 1271, 1638],
backgroundColor: 'rgba(0, 99, 132, 0.6)',
borderColor: 'rgba(0, 99, 132, 1)',
yAxisID: "y-axis-density"
};
var gravityData = {
label: 'Gravity of Planet (m/s2)',
data: [3.7, 8.9, 9.8, 3.7, 23.1, 9.0, 8.7, 11.0],
backgroundColor: 'rgba(99, 132, 0, 0.6)',
borderColor: 'rgba(99, 132, 0, 1)',
yAxisID: "y-axis-gravity"
};
var planetData = {
labels: ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"],
datasets: [densityData, gravityData]
};
var chartOptions = {
scales: {
xAxes: [{
barPercentage: 1,
categoryPercentage: 0.6
}],
yAxes: [{
id: "y-axis-density"
}, {
id: "y-axis-gravity"
}]
}
};
var barChart = new Chart(densityCanvas, {
type: 'bar',
data: planetData,
options: chartOptions
});
Here, we have created two y-axes with unique ids, and they have been assigned to individual datasets using the yAxisID key. The barPercentage and categoryPercentage keys have been used here to group the bars for individual planets together. Setting categoryPercentage to a lower value increases the space between the bars of different planets. Similarly, setting barPercentage to a higher value reduces the space between bars of the same planet.
In this tutorial, we have covered all the aspects of line charts and bar charts in Chart.js. You should now be able to create basic charts, modify their appearance, and plot multiple datasets on the same chart without any issues. In the next part of the series, you will learn about the radar and polar area charts in Chart.js.
I hope you liked this tutorial. If you have any questions, please let me know in the comments.
|