Fake array slicing operator: reduce it

Is there any innovative way to make the “print” shorter without too much confusion? And which of the “prints” do you like best?

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 a slice syntax that is in Python / Ruby, in PHP for example.

 a[1:3] a[1,3] a[1..3] 

to do this in PHP you need to quote as $a["1:3"] ($ a is a class with an ArrayAccess interface), so I thought there were other ways, $a[(0)._.(0)] This is too long.

+4
source share
5 answers

What do you want to do? concatenate strings? use implode :

 echo implode('_', array(0, 0)); 

not shorter, but definitely less confusing, more readable and best conveys the intention


now edit that question has enough information:

you have a class that implements the ArrayAccess interface.

why not use decimal numbers to reach your cutting operator?

  $a = new PythonArray(array(1, 2, 3, 4, 5)); $b = $a[1.3]; 

you must then convert the number to a string and divide by period. You can also use floor to get both parts. then delegate array_slice :

  list($start, $len) = explode('.', (string)$offset); return array_slice($internal_array, $start, $len); 

remember that floating point precision issues may occur. what is wrong with quotation marks? two extra characters are not so bad.

+1
source

If you intend to remove the confusion, you really should not write such code, because it is one step lower than obfuscation.

+5
source

Since this is PHP, you can make it a little shorter using echo instead of printing. A.

+1
source

The direct approach works well.

Comparison

 print "0_0"; print _j(0,0); 

I'm not quite sure your goal is here.

+1
source

This is the shortest and not confusing way: p

 echo "0_0"; 
0
source

All Articles