It has been over a year since i blogged. It seems work is always taking over my free time. But I will never let my blog die.
Today i read an article about idiomatic python and I thought lets reproduce the code in php as an exercise. Working with .NET languages makes me rusty.
I will stay away from the style examples to avoid discussions that go nowhere.
I'm going to take the subtitles of the article and add the php code, enjoy!
Avoid using a temporary variable when swapping two variables
$a = 'a'; $b = 'b';
list($foo,$bar) = array($bar,$foo);
Use tuples to unpack data
There are no tuples in php, an array will do.
$list_from_comma_seperated_value_file = array('dog','Fido',10);
list($animal, $name, $age) = $list_from_comma_seperated_value_file;
Use ''.join when creating a single string for list elements
Join in php is an alias for implode. In php 5.4 square brackets can be used to create an array.
$result_list = ['True','False','File not found'];
$result_string = join('',$result_list);
Use the 'default' parameter of dict.get() to provide default values
The closest thing in php is the ternary operator.
$log_severity = isset($configuration['severity'])
? $configuration['severity'] : $loginfo;
Use Context Managers to ensure resources are properly cleaned up
It would be nice to have this in php.
Avoid repeating variable name in compound if Statement
if(array_search($name,['Tom', 'Dick', 'Harry']) !== false) {
$generic_name = true;
}
Use list comprehensions to create lists that are subsets of existing data
The closest thing in php is to use an anonymous function and array_map.
$some_other_list = range(1,100);
$my_weird_list_of_numbers = array_map(
function($element){
if(is_prime($element){ return $element + 5; }
}
,$some_other_list);
Use the 'in' keyword to iterate over an Iterable
The foreach loop in php uses the keyword as
$my_list = [ 'Larry' , 'Moe' , 'Curly' ];
foreach($my_list as $element){
echo $element;
}
Use the enumerate function in loops instead of creating an 'index' variable
No need to use a function in a foreach loop to do this. It feels good to write that.
foreach($my_list as $index=>$element){
echo $element;
}
PS note to self: create own blogger theme and never use blogger compose again.
No comments:
Post a Comment