Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ArrayAccess interface) so I was thinking if there is some otherways, $a[(0)._.(0)] This is too long.

like image 335
Codler Avatar asked Feb 27 '23 11:02

Codler


2 Answers

If you intend to remove confusion, you really shouldn't be writing such code because it's a step short of obfuscation.

like image 172
bcosca Avatar answered Mar 07 '23 10:03

bcosca


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.

like image 23
knittl Avatar answered Mar 07 '23 12:03

knittl