Fake array slicing operator: Make it shorter
Is there some innovative way to make the "print" shorter without too much confusion? And which of the "print" do you like most?
define('_','_');
function _j($a, $b) {
return $a._.$b;
}
// Output 0_0
print (0)._.(0);
print _j(0,0);
Update
What I want to do is to have slice syntax that are in Python/Ruby into PHP eg.
a[1:3]
a[1,3]
a[1..3]
to make it into PHP you need to quote like this $a["1:3"]
($a is a class with 开发者_StackOverflow社区ArrayAccess interface) so I was thinking if there is some otherways, $a[(0)._.(0)]
This is too long.
If you intend to remove confusion, you really shouldn't be writing such code because it's a step short of obfuscation.
what do you want to do? concatenate strings? use implode
:
echo implode('_', array(0, 0));
not shorter, but definitely less confusing, more readable and it best conveys the intention
edit now that the question has enough information:
you have a class which implements the ArrayAccess interface.
why not use decimal numbers to achieve your slicing operator?
$a = new PythonArray(array(1, 2, 3, 4, 5));
$b = $a[1.3];
you should then be able to convert the number to a string and split on the period. you could also use floor
to get both parts. then delegate to array_slice
:
list($start, $len) = explode('.', (string)$offset);
return array_slice($internal_array, $start, $len);
be aware though, there might be problems with floating point precision. what's wrong with using quotes though? two extra characters is not too bad.
Since it's PHP, you could make it a tiny bit shorter by using echo instead of print.
The straight forward approach works well.
Compare
print "0_0";
print _j(0,0);
I'm not entirely sure what your goal is here.
This is the shortest and non confusing way :p
echo "0_0";
精彩评论