-3

I have to translate a python code to php, but I don't know how this python code work in php :

dec = data_ar[4:len(data_ar)]

I don't know what's the colon ":" between [ ]! Thanks

3 Answers3

3

That's just Python's array slicing notation, so I think what you want is array_slice:

array_slice($data_ar, 4);
Community
  • 1
  • 1
DaoWen
  • 32,589
  • 6
  • 74
  • 101
3

If you're trying to achieve the exact functionality in PHP:

<?php
$data_ar = array(1,2,3,4,5,6,7);
$dec = array_slice($data_ar, 4, count($data_ar)-4);

Now, the interesting thing here is the len(data_ar). If you provide the colon without a second argument, "until the end" is assumed. So this piece of functionality should actually have been written like so:

dec = data_ar[4:]

Likewise, we can modify the PHP side of things to reflect the same simplicity:

<?php
$data_ar = array(1,2,3,4,5,6,7);
$dec = array_slice($data_ar, 4);
print_r($dec); // Returns array(5,6,7)
Joshua Burns
  • 8,268
  • 4
  • 48
  • 61
  • As with his Python example, there's no need to recompute the length. `array_slice` goes to the end of the array by default. (Check the documentation.) – DaoWen Mar 20 '13 at 21:38
  • +1 for using [`print_r`](http://www.php.net/manual/en/function.print-r.php). Knowing about that function will probably help him a lot with debugging. – DaoWen Mar 20 '13 at 21:42
  • I just read your explanation and decided to (temporarily) change my +1 to -1 since this is wrong: _Offsets start at zero, so they're actually grabbing one more than the length of the list._ Read the link in my answer on Python array slicing and fix your answer. When you've fixed it I'll give back the +1! – DaoWen Mar 20 '13 at 21:44
  • i think maybe you're mis-understanding something here. are you a python programmer yourself? if `mystr = 'hiho'` and you print `mystr[1:]` `iho` is printed. nothing about my statement is incorrect. – Joshua Burns Mar 20 '13 at 21:53
  • @JoshuaBurns - I don't use Python much, but I know enough to know that your statement about going off the end of the list is wrong. As with a lot of other slicing functions, the first index arg is _inclusive_ and the second is _exclusive_. I.e. you _must_ specify an index that's one _after_ the last element you want. – DaoWen Mar 21 '13 at 00:03
0

Colon means "to" in most languages. This means index 4 to the length of the array (the end).

In PHP, you can use array_slice like this:

$dec = array_slice($data_ar, 4)
Christian Stewart
  • 15,217
  • 20
  • 82
  • 139