[PHP-DEV] Re: [Discussion] FFI in PHP

2017-02-05 Thread Alex Bowers
And here is the previous messaging without borked formatting. Sorry folks.


FFI RFC
==

There are many languages that support an FFI implementation.

NodeJS
Python
C++
Ruby

FFI allows you to call a native C function without requiring the
boilerplate of an extension to be written.

There are several benefits to having FFI

- Performance
- Shareability / Bundling
- Common functionality between languages

Performance
===
Although less pronounced than the 5.x versions, there is still a
performance benefit to having native C code over PHP code. For
example, you could utilise threading inside of your FFI methods, which
PHP does not expose the ability to do.

Shareability
===

If you wish to implement some of your source code in C, the current
way to share it is to build it as an extension. This is cumbersome,
and restricts use-cases such as shared hosting, where the ability to
install your own extensions is probably restricted. However, with FFI,
the shared object can be loaded from any location, and so that
restriction is no longer in place.

They could even be distributed via composer.

Common functionality between languages
===

If you have some complex logic that needs to be replicated in several
languages for whatever reason; implementing it several times over
would lead to uncertain bugs and technical debt increasing heavily. If
you could share the same logic amongst them all using FFI, then this
is no longer an issue.

Example
===

Take an example of a rust program that takes two numbers in and gives
you the sum of them.

```rust
#[no_mangle]
pub extern fn add(a: i32, b: i32) -> i32 {
a + b
}

```

with the Cargo.toml file containing:

```
[package]
name = "math"
version = "0.1.0"
authors = ["Alex Bowers "]

[dependencies]

[lib]
name = "math"
crate-type = ["dylib"]
```

`cargo build --release` will create `.so`, `.dylib`, or `.dll` files
depending on your system.

These should be usable within PHP using the exposed functions.

```php
$math = ffi("/path/to/math.so");
$result = $math->add(1, 5);

echo $result; // 6
```

With the implementation at its most basic level, calling the `add`
method with incorrect parameters would likely cause a segfault.

A way around that could be that the methods are not immediately
exposed, but have to be configured.

Something like:

```php
$math = ffi("/path/to/math.so");
$math->add(1, 5); // Throws RuntimeException, method not configured

$math->configure('add', int $a, int $b);

$math->add(1, 5); // 6
$math->add('a', 5); Fatal error: Uncaught TypeError: Argument 1 passed
to add() must be of the type integer, string given
```

Prior art:
===
https://pecl.php.net/package/ffi - Last release > 13
yearshttps://github.com/mgdm/MFFI - Not stable, last commit > 1 year,
no releases


[PHP-DEV] [Discussion] FFI in PHP

2017-02-05 Thread Alex Bowers
Hello All,

I'd like to start a discussion around an FFI RFC

FFI RFC == There are many languages that support an FFI implementation.
NodeJS Python C++ Ruby FFI allows you to call a native C function without
requiring the boilerplate of an extension to be written. There are several
benefits to having FFI - Performance - Shareability / Bundling - Common
functionality between languages Performance === Although less pronounced
than the 5.x versions, there is still a performance benefit to having
native C code over PHP code. For example, you could utilise threading
inside of your FFI methods, which PHP does not expose the ability to
do. Shareability
=== If you wish to implement some of your source code in C, the current way
to share it is to build it as an extension. This is cumbersome, and
restricts use-cases such as shared hosting, where the ability to install
your own extensions is probably restricted. However, with FFI, the shared
object can be loaded from any location, and so that restriction is no
longer in place. They could even be distributed via composer. Common
functionality between languages === If you have some complex logic that
needs to be replicated in several languages for whatever reason;
implementing it several times over would lead to uncertain bugs and
technical debt increasing heavily. If you could share the same logic
amongst them all using FFI, then this is no longer an issue. Example === Take
an example of a rust program that takes two numbers in and gives you the
sum of them. ```rust #[no_mangle] pub extern fn add(a: i32, b: i32) -> i32 { a
+ b } ``` with the Cargo.toml file containing: ``` [package] name =
"math" version
= "0.1.0" authors = ["Alex Bowers "] [dependencies]
[lib] name = "math" crate-type = ["dylib"] ``` `cargo build --release` will
create `.so`, `.dylib`, or `.dll` files depending on your system. These
should be usable within PHP using the exposed functions. ```php $math =
ffi("/path/to/math.so"); $result = $math->add(1, 5); echo $result; //
6 ``` With
the implementation at its most basic level, calling the `add` method with
incorrect parameters would likely cause a segfault. A way around that could
be that the methods are not immediately exposed, but have to be
configured. Something
like: ```php $math = ffi("/path/to/math.so"); $math->add(1, 5); // Throws
RuntimeException, method not configured $math->configure('add', int $a, int
$b); $math->add(1, 5); // 6 $math->add('a', 5); Fatal error: Uncaught
TypeError: Argument 1 passed to add() must be of the type integer, string
given ``` Prior art: === https://pecl.php.net/package/ffi - Last release >
13 years https://github.com/mgdm/MFFI - Not stable, last commit > 1 year,
no releases


Re: [PHP-DEV] [RFC] [VOTE] Libsodium as a core extension in PHP 7.2

2017-02-03 Thread Alex Bowers
On 4 February 2017 at 00:04, Nikita Popov  wrote:

> On Sat, Feb 4, 2017 at 12:54 AM, Scott Arciszewski 
> wrote:
>
> > On Fri, Feb 3, 2017 at 6:19 PM, Yasuo Ohgaki  wrote:
> >
> > > Hi Scott and all,
> > >
> > > On Sat, Feb 4, 2017 at 5:44 AM, Scott Arciszewski  >
> > > wrote:
> > >
> > >> I've opened the vote for the libsodium RFC.
> > >>
> > >> https://wiki.php.net/rfc/libsodium
> > >>
> > >> See https://externals.io/thread/626 for the previous discussion
> topics.
> > >>
> > >> The vote closes at 21:00 UTC (4 PM Eastern Time) next Friday.
> > >>
> > >
> > > I voted for "No, sodium_foo" syntax in order to be consistent with
> > > existing procedural APIs.
> > > 2/3 majority wouldn't fit nicely. What it would be if vote result is
> 51%
> > > vs 49%?
> > > More than half is good enough for 2nd vote choice. IMO.
> > >
> > > Regards,
> > >
> > > --
> > > Yasuo Ohgaki
> > > yohg...@ohgaki.net
> > >
> > >
> > I like \Sodium\foo instead of sodium_foo, but it deviates from the norm.​
> > ​ If we're going to break the norm, we should do so on a stronger
> majority
> > than 50%+1.
> >
> > Also, I thought the rules changed so *_everything_* needed 2/3 now?​
> >
>
> The usual rule is that "secondary" votes use 50% majority, to avoid bias in
> one direction or the other.
>
> Regards,
> Nikita
>

Would it not be possible for _both_ to be supported? It would be just an
alias


Re: [PHP-DEV] Re: [Concept] Magic Casting

2016-12-02 Thread Alex Bowers
So I guess the new logic is, that the class being casted to, MUST have zero
or one required parameter.

It must not cast if already the same type.

It must not cast to its own type (infinite loop)


Re: [PHP-DEV] Re: [Concept] Magic Casting

2016-12-02 Thread Alex Bowers
On 2 December 2016 at 15:17, Andrey Andreev  wrote:

> Honestly, I don't see how a new method is in any way beneficial.


I see your point now, and actually agree. An interface would be suitable
and probably a better way to implement it.


Re: [PHP-DEV] Re: [Concept] Magic Casting

2016-12-02 Thread Alex Bowers
Sorry for dupe, hit reply not reply-all.

I don't see how the interface is equivalent.

The benefit of this, is that you can convert types passed into a method to
the type you expect automagically, Castable wouldn't allow that, only a new
magic method (or reflection and user land code possibly?) would allow this.

As for the limitation of only one parameter being accepted, what would the
other possible parameters be?

Since this is based entirely on the casted variable, there can only
possibly be one variable there, the one passed into that position in the
functions arguments.

Arguably, this feature would resolve some bugs in peoples code, because it
can allow better enforcing of types.

Currently, a place that accepts a Collection would not be able to type hint
it if it wants to also accept an array, instead it would have to check and
change inside the method, but that shouldn't be the role of the method.

The method just wants to assume, and work on the assumption that it is the
correct type, but without losing flexibility.

The ability to cast to your own type automatically would help with this
assumption, as now everywhere would be able to assume Collection, and use
it as so, but allow the current flexibility of arrays being passed in also.


Fwd: [PHP-DEV] Re: [Concept] Magic Casting

2016-12-02 Thread Alex Bowers
Sorry for forward, hit reply not reply all.

-- Forwarded message --
From: Alex Bowers 
Date: 2 December 2016 at 14:16
Subject: Re: [PHP-DEV] Re: [Concept] Magic Casting
To: David Rodrigues 


var_dump was just an example to "show what type the variable is", and
completely untested. Consider replacing that line with anything that would
make it clear to you that it is now no longer an array, but a Collection
for example.


Fwd: [PHP-DEV] Re: [Concept] Magic Casting

2016-12-02 Thread Alex Bowers
Sorry for forward. Hit reply, not reply-all.

-- Forwarded message --
From: Alex Bowers 
Date: 2 December 2016 at 14:31
Subject: Re: [PHP-DEV] Re: [Concept] Magic Casting
To: David Rodrigues 


Another benefit this would give frameworks / user land code is the ability
to mock / simulate having scalar object types.

For instance, A class called `Str` could be used to cast all "string"
inputs to its type, and then everywhere in the framework / user land code,
based on __cast() it could cast them all to a Str instance, and be used
with methods on.

This will allow

$string->toUpperCase() to be possible etc, whilst acting on a plain string.

On 2 December 2016 at 14:30, Alex Bowers  wrote:

> To me, in pseudo logic it would work as so:
>
> Currently it does this:
>
> A method with the signature of function_name(Collection $collection) has
> been called. The parameter I have is of type Collection. Let it continue;
> or alternatively, the parameter is not of type Collection, throw the error.
>
> The new method will be:
>
> A method with the signature of function_name(Collection $collection) has
> been called. The parameter I have is of type collection. let it continue.
>
> Alternatively,
> The parameter is not of type collection, does Collection implement a
> __cast() magic method. If it does, Pass the parameter into that __cast()
> method. If the response is an instance of Collection, let it through. If it
> is not, throw the error.
>
> As to how this would be implemented, r how the engine is built. This is
> not something I am aware of really. I will be willing to learn, and assist
> somebody / get assistance in the building of this feature, but it would
> take me a lot longer than it would take a real core member to do.
>
> But effectively, it will call Type::__cast()
>


Re: [PHP-DEV] Re: [Concept] Magic Casting

2016-12-02 Thread Alex Bowers
On 2 December 2016 at 14:46, Andrey Andreev  wrote:

> It enables magic behavior, that's the opposite of enforcement ... If you
> want to enFORCE something, you force the developer to do something, you
> don't auto-magically do the thing for them.


This magic behaviour would be for enforcement, because you are now
enforcing that the passed in type is acceptable to the contract of
Collection. It can be an array, because arrays can be converted to a
Collection, and it is down to the __cast() method to determine whether that
is a suitable conversion, but it allows you to enforce a suitable parameter
is passed in. Currently, to accept bot ha Collection and an array, you
would have to not enforce anything, and inside of the method handle the
conversion or exceptions.


Re: [PHP-DEV] Re: [Concept] Magic Casting

2016-12-02 Thread Alex Bowers
On 2 December 2016 at 14:46, Andrey Andreev  wrote:

> What I meant is - you cannot cast to a class that requires more than one
> dependency to be instantiated - that's the obvious limitation.


Ah yes, that is certainly true, unless the other parameters can be
determined / derived (e.g., injection using a container).


Re: [PHP-DEV] Re: [Concept] Magic Casting

2016-12-02 Thread Alex Bowers
On 2 December 2016 at 14:46, Andrey Andreev  wrote:

> A magic method is essentially an implicit interface ...
> The interface itself does nothing. But when it is implemented, the engine
> will know that the class constructor is public and accepts a single
> parameter - thus, also knowing that it could try to do a new
> ClassName($yourParameterHere)
>

The interface would not work though, because there should be some logic in
place too. For example, if you accept, but convert an array, or an array of
arrays etc differently. Or would this be logic that should be placed inside
of the constructor, and the castable will just offload to a new
construction?


Re: [PHP-DEV] Re: [Concept] Magic Casting

2016-12-02 Thread Alex Bowers
Damn. I must have done that to a lot of emails. Gonna have to resend them
all when I get home. Sorry folks for dupes.

On 2 December 2016 at 14:46, Andrey Andreev  wrote:

> Hi again,
>
> On Fri, Dec 2, 2016 at 4:19 PM, Alex Bowers  wrote:
>
>> I don't see how the interface is equivalent.
>>
>> The benefit of this, is that you can convert types passed into a method
>> to the type you expect automagically, Castable wouldn't allow that, only a
>> new magic method (or reflection and user land code possibly?) would allow
>> this.
>>
>
> A magic method is essentially an implicit interface ...
> The interface itself does nothing. But when it is implemented, the engine
> will know that the class constructor is public and accepts a single
> parameter - thus, also knowing that it could try to do a new
> ClassName($yourParameterHere)
>
>
>>
>> As for the limitation of only one parameter being accepted, what would
>> the other possible parameters be?
>>
>> Since this is based entirely on the casted variable, there can only
>> possibly be one variable there, the one passed into that position in the
>> functions arguments.
>>
>>
> What I meant is - you cannot cast to a class that requires more than one
> dependency to be instantiated - that's the obvious limitation.
>
>
>> Arguably, this feature would resolve some bugs in peoples code, because
>> it can allow better enforcing of types.
>>
>
> It enables magic behavior, that's the opposite of enforcement ... If you
> want to enFORCE something, you force the developer to do something, you
> don't auto-magically do the thing for them.
>
> P.S.: I suppose you've hit "Reply" instead of "Reply All"? I was the only
> recepient of the message I'm quoting.
>
> Cheers,
> Andrey.
>
>


[PHP-DEV] Re: [Concept] Magic Casting

2016-12-02 Thread Alex Bowers
And because the email formatting appears bad (at least in externals.io)

Here it is in a gist:
https://gist.github.com/alexbowers/9520c8df746249ecae2d9c7aad2e54ae


[PHP-DEV] Re: [Concept] Magic Casting

2016-12-02 Thread Alex Bowers
Sorry, forgot a little bit of information.

If the type passed is already satisfactory (an instance), then __cast is
NOT called.


[PHP-DEV] [Concept] Magic Casting

2016-12-02 Thread Alex Bowers
Hello All,

In PHP we currently have the ability to type hint classes in method
signatures, however, sometimes it would be useful to convert the items to a
different instance / type.

An example is collections and arrays. If implemented properly, an array and
a collection could be used interchangeably, although a collection may be
preferred. For consistency, having the ability to dynamically cast from an
array to a collection would be very useful.

An idea of how this may look would be:

items = $items;
}

   ...

public function __cast(array $items) : Collection
{
return new static($items)
}
}

--

The __cast method MUST return an instance of itself, so that when called
like so:

function convert_me(Collection $collection)
{
var_dump($collection);
}

convert_me([1,2,3]);

the result there would be a Collection instance, instead of an array.

If the type passed is not accepted by __cast() or __cast() throws an
exception, then the current errors of invalid type are thrown, or perhaps
the custom exception message.

I'm not sure if this has been proposed before, and if it has, please could
someone assist in me finding it, I couldn't find it by a quick search on
the wiki.php.net/rfc page.

Thanks.
Alex.


Re: [PHP-DEV] number_format() = "-0.00"

2016-11-25 Thread Alex Bowers
Php doesn't have a concept of negative zero except in a string instance.
And the main use case for this is displaying the number as a string which
has very few real world use cases as being a negative zero.

On 25 Nov 2016 9:05 am, "Craig Duncan"  wrote:

> On 25 November 2016 at 08:58, Sherif Ramadan 
> wrote:
>
> > I'm pretty sure this is covered by the language reference [
> > http://php.net/language.types.float] as per precision of floating point
> > numbers in PHP. Though I don't see much harm in adding a note with
> > references there to the documentation for number_format(), if that's what
> > you meant.
> >
>
> Yeh, I'd imagine that's where most people will go looking when they
> encounter this issue
>


Re: [PHP-DEV] Re: [RFC] Traits with interfaces

2016-02-22 Thread Alex Bowers
Would a fair solution to this be having the using class define whether to
inherit the implementations? Perhaps a new keyword akin to 'propagated', so
the code will read

Class Foo {
   Use propagated TraitName;
}

Only then will the implementations from that trait bubble through. If it
isn't declared then the implementations are not visible. This should keep
all backwards compatibility and keep code readable since now we can
immediately tell which traits being used do we want the implementations for
in the main class.
On 22 Feb 2016 20:19, "Kevin Gessner"  wrote:

> On Thu, Feb 18, 2016 at 4:13 PM, Kevin Gessner  wrote:
>
> > On Wed, Feb 17, 2016 at 2:05 PM, Kevin Gessner 
> wrote:
> >
> >> I've created a proper RFC wiki page here with the draft:
> >> https://wiki.php.net/rfc/traits-with-interfaces
> >>
> >> It includes more detail and several example code snippets.  Thanks all
> >> for your feedback so far.
> >>
> >
> > I've just updated the RFC to v0.2, presenting two proposals to be voted
> > separately: one to allow traits to declare and implement interfaces, and
> a
> > second (dependent on the first) to propagate interface declarations from
> > traits to classes.
> >
>
> I've created a php-src pull request for Proposal 1 of the RFC, allowing
> traits to declare and implement interfaces:
> https://github.com/php/php-src/pull/1773
>
> Reviews and feedback welcome!
>
> I haven't yet started on an implementation for Proposal 2.
>
> Cheers
> -- Kevin
>


Re: [PHP-DEV] Re: [VOTE] Reclassify E_STRICT notices

2015-04-01 Thread Alex Bowers
Is the last one really a strict? Sounds like it should be a warning to me.
Similar to when you for each over something not an array
On 1 Apr 2015 15:58, "Nikita Popov"  wrote:

> On Wed, Mar 25, 2015 at 5:14 PM, Nikita Popov 
> wrote:
>
> > On Sun, Mar 15, 2015 at 4:46 PM, Nikita Popov 
> > wrote:
> >
> >> Hi internals!
> >>
> >> To ensure we have no shortage of new RFC votes...
> >>
> >> https://wiki.php.net/rfc/reclassify_e_strict#vote
> >>
> >> Voting is open for ten days :)
> >>
> >
> > RFC is accepted with 28 votes in favor and 4 against.
> >
>
> The RFC is now implemented. However while landing the patch I noticed that
> I missed a number of E_STRICT notices in libraries. In particular:
>
> * mktime() without arguments throws "You should be using the time()
> function instead"
>
> * htmlentities() with some encodings like EUC-JP throws "Only basic
> entities substitution is supported for multi-byte encodings other than
> UTF-8; functionality is equivalent to htmlspecialchars"
>
> * mysqli::next_result() if there is no next result throws "There is no next
> result set"
>
> While the first one sounds like something that should be deprecated, I
> couldn't say what to do with the other two.
>
> Nikita
>


Re: [PHP-DEV] password_hash() deprecate salt option - thoughts?

2015-03-31 Thread Alex Bowers
I think deprecating it is a good idea, and looking at the documentation it
does mention that not providing it is the intended option; so it isn't a
complete surprise for it to become deprecated.

On 31 March 2015 at 19:49, Anthony Ferrara  wrote:

> All,
>
> Ever since we introduced password_hash() in 5.5, I've been watching
> its usage as much as possible. I've setup google alerts and such, as
> well as auditing implementations I've found on github to try to
> understand how it's used.
>
> One thing has become abundantly clear to me: the salt option is
> dangerous. I've yet to see a single usage of the salt option that has
> been even decent. Every usage ranges from bad (passing mt_rand()
> output) to dangerous (static strings) to insane (passing the password
> as its own salt).
>
> I've come to the conclusion that I don't think we should allow users
> to specify the salt. The crypt() API still exists if users have a need
> to generate their own salt. Having it in the simplified API is simply
> adding a risk factor without any significant justification.
>
> So I'd like to hear your thoughts about raising E_DEPRECATED when the
> salt option is specified in 7.0, with ultimately removing the option
> in a later version.
>
> Additionally, I know this is after the RFC freeze deadline, so if you
> want to postpone the deprecation to 7.1, that's fine. I just think
> it's worth discussion (and if there's consensus to put it in 7.0, then
> great).
>
> Thanks,
>
> Anthony
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>


Re: [PHP-DEV] [RFC] Fix the Tenary Operator -- Please!? Please?

2015-03-26 Thread Alex Bowers
The deadline for PHP 7 features has passed

On 26 March 2015 at 20:54, Michael Morris  wrote:

> Per PHPsadness...
>
> http://phpsadness.com/sad/30
>
> Since 7 is allowed to have BC breaks this would be the time to fix this.
>
> I'll let someone with more seniority actually write this up - but please,
> please fix this - it's a very long standing annoyance.
>


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-21 Thread Alex Bowers
Would it make more sense then to have a RFC for array by positional index.
No range or anything initially (that will be a separate RFC), but simply to
get the value of an array by positional index?

$array[*4] to get the item in position 4.


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
On 20 March 2015 at 23:03, Stanislav Malyshev  wrote:

> $array[*1:4] by reference -
> what is actually passed?
>

Implementation is not something I have looked into for this yet, so I am
unsure how this would be possible; but by passing $array[*1:4], you'd be
passing an extracted array which is a reference to the original array. Such
that changing the sub array can change the parent array.


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
On 20 March 2015 at 22:12, Stanislav Malyshev  wrote:

> You're not using the keys in foreach, so why you need to preserve them?


This was merely an example of the features equal part in current code, not
a real life use case.

Using the new syntax will keep the keys preserved, therefore any example
showing how to do the same *must* do the same, which preserving keys does.

This may be not so easy to implement - imagine passing $array[*1:4] by
> reference.


This would be the same as doing
$array[array_keys($old_array)[1]] = $new_array[0];
$array[array_keys($old_array)[2]] = $new_array[1];
$array[array_keys($old_array)[3]] = $new_array[2];
$array[array_keys($old_array)[4]] = $new_array[3];

The new syntax helps clean that up, by doing:

$array[*1:4] = [1,2,3,4];

There is nothing to pass by reference that is different, the array is still
$array, it is just having the values replaced in bulk by index (not by key)

This sort of code would be needed:

 1, 1 => 2, 5 => 3, 7 => 4, 4 => 5, 2 => 6, 14 => 7, 55
=> 8];

$new_array_values = ['foo', 'bar', 'baz'];

// To replace the third, fourth and fifth element.

$old_array[array_keys($old_array)[3]] = $new_array_values[0];
$old_array[array_keys($old_array)[4]] = $new_array_values[1];
$old_array[array_keys($old_array)[5]] = $new_array_values[2];

var_dump($old_array);

Instead of, what is in my opinion, much cleaner:

 1, 1 => 2, 5 => 3, 7 => 4, 4 => 5, 2 => 6, 14 => 7, 55
=> 8];

$new_array_values = ['foo', 'bar', 'baz'];

$old_array[*3:5] = $new_array_values;

var_dump($old_array);


There is the array_splice method that can do the same thing, however this
to me is less obvious as to what is happening:

 1, 1 => 2, 5 => 3, 7 => 4, 4 => 5, 2 => 6, 14 => 7, 55
=> 8];

$new_array_values = ['foo', 'bar', 'baz'];

// To replace the third, fourth and fifth element.

array_splice($old_array, 3, 3, $new_array_values);

var_dump($old_array);


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
>
> Why not use array_slice for it?


There certainly are ways to do most of what this RFC covers, however most
of them don't lend themselves well to clean code in my opinion.

Thats why this RFC is listed as being syntactic sugar.

On 20 March 2015 at 21:30, Stanislav Malyshev  wrote:

> Hi!
>
> > It would give different results, for a reason. There is currently no way
> > to get an array item by positional index, whilst preserving the keys.
>
> I imagine having such way may be useful. However, reusing array access
> syntax for that does not look like a good idea, since it would look like
> existing array syntax but work completely different. Why not use
> array_slice for it?
> --
> Stas Malyshev
> smalys...@gmail.com
>


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
>
> // alternative old
>   foreach(array_slice($results, 0, 9) as $result) {
>   echo $result . "\n"; // 1 2 3 4 5 6 7 8 9
>   }
> Not so bad, in my opinion.


To be the same, your example would have to be:

// alternative old
  foreach(array_slice($results, 0, 9, true) as $result) {
  echo $result . "\n"; // 1 2 3 4 5 6 7 8 9
  }

since this will preserve the array keys.

This was a quick off the top of my head example; there is also the benefit
of overwriting multiple array items with a single line

$array[*1:4] = [1,2,3,4]; // Sets array items 1 through 4 to be the values
(and keys if provided), of the array assigned.

$array[*1:] = [1,2,3,4]; // Sets array items 1 to the end to be values (and
keys if provided), of the array assigned. This will also wipe out any
additional information to the end of the array. Keeping anything before the
first item, but extending until the end.

This would be similar to array_replace, however that works from keys, not
positions.


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
On 20 March 2015 at 20:52, Stanislav Malyshev  wrote:

> I'm not sure how such operation would be useful, and it definitely would
> not be intuitive, as $array[0] and $array[0:1] (assuming non-inclusive
> semantic, or [0:0] with inclusive semantics) would return completely
> different things. That would happen even if the array has only numeric
> keys! This is the main problem with this syntax - unlike most languages
> where it is used, PHP arrays are not vectors, they are ordered hashmaps.
> Sometimes this is very convenient, sometimes - like for this syntax - it
> is not. I think this is the major reason why such proposals failed in
> the past.
>

It would give different results, for a reason. There is currently no way to
get an array item by positional index, whilst preserving the keys.

This RFC will allow that, with the inclusion of the symbol that will be
required for this RFC (slicing by key can be a separate RFC; and is not
covered by this RFC).

So, if i want to get the items from position 1 through 5, I can use [*1:5]
and I will get an array of the items in position 1,2,3,4 and 5; regardless
of their keys, as an array.


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
The latest comments in this thread are talking about having a symbol before
the range to show that it is by positional index. Current propositions for
this are ^ and *.

I'm not sure how such operation would be useful


Anywhere on the front-end where a foreach() is used, and expects at most
say, 10 items. But the full dataset is fetched back (to show a summary
after the first 10 or whatever other reason).

The old code would have required a counter, the new code does not. This
would make it cleaner for the front-end developer to understand.

 9) break;
echo $result . "\n"; // 1 2 3 4 5 6 7 8 9
}

// New

foreach($results[*:9] as $result) {
echo $result . "\n"; // 1 2 3 4 5 6 7 8 9
}

---

$string = "abcdefghijklmnop";

// Old
echo substr($string, 0, 5); // abcde

// New
echo $string[*:4]; // abcdef

This is just a few basic examples, but should show that there is a use case
for it.

On 20 March 2015 at 20:52, Stanislav Malyshev  wrote:

> Hi!
>
> >> My proposal is something similar to Pythons slice, in PHP this would
> look
> >> like:
> >>
> >> $slided = $array[1:4]
> >>
> >> This will get the elements in positions 1,2,3,4. (1 through 4
> inclusive),
> >> ignoring the actual key of the array. The result for an array will be an
> >> array with the keys preserved, in the same order.
>
> I'm not sure how such operation would be useful, and it definitely would
> not be intuitive, as $array[0] and $array[0:1] (assuming non-inclusive
> semantic, or [0:0] with inclusive semantics) would return completely
> different things. That would happen even if the array has only numeric
> keys! This is the main problem with this syntax - unlike most languages
> where it is used, PHP arrays are not vectors, they are ordered hashmaps.
> Sometimes this is very convenient, sometimes - like for this syntax - it
> is not. I think this is the major reason why such proposals failed in
> the past.
>
> --
> Stas Malyshev
> smalys...@gmail.com
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
>
> There’s no existing unary form of  * and ^, though, so I think they’d both
> be available in this context (^ is my preference).


I think that is also my preference too.

On 20 March 2015 at 20:17, John Bafford  wrote:

>
> On Mar 20, 2015, at 16:10, Sean Coates  wrote:
>
> >> I posted four suggestions earlier,
> >>
> >> They were:
> >>
> >> @
> >> &
> >> *
> >> ^
> >>
> >> My favourites are the asterisk or caret.
> >
> > That’s no different than `@` being invalid because it’s already in use.
> >
> > $ php -a
> > Interactive shell
> >
> > php > define('a', 1);
> > php > define('b', 2);
> > php > echo @a . "\n";
> > 1
> > php > echo (a&b) . "\n";
> > 0
> > php > echo (a*b) . "\n";
> > 2
> > php > echo (a^b) . "\n";
> > 3
> > php >
> >
> > However: `☃` has a long history of being available to PHP.
> >
> > S
> >
>
> There’s no existing unary form of  * and ^, though, so I think they’d both
> be available in this context (^ is my preference).
>
> Overloading unary & would probably also work in this context, but
> personally, I think that & is too overused.
>
> -John


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
On 20 March 2015 at 20:10, Sean Coates  wrote:

> That’s no different than `@` being invalid because it’s already in use.


The syntax would be [*from:to], which would currently throw a parse error
(since asterisk is required to be placed between two numbers), so this
would be different.

Alternatively, an underscore could be used

This would then look like [_from:to]

Also, another option would be to not use the square bracket syntax at all,
and move towards angled brackets for positional indexing.

This would then be $array<1:2> to get items in positions 1 and 2.


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
>
> The concept itself can still work, but it’d need a token other than @.


This is the symbol currently being used for examples, but thats all it is
currently. Nothing is set in stone (and most likely will change), not just
for this reason but for the reason that I mentioned earlier in the thread
that the @ symbol has bad connotations, and avoiding these connotations
would benefit the RFC.

I posted four suggestions earlier,

They were:

@
&
*
^

My favourites are the asterisk or caret.


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
Is everybody happy with the RFC being called 'Slice Operator', or is there
a better name for it?

On 20 March 2015 at 18:17, Rowan Collins  wrote:

> Leigh wrote on 20/03/2015 16:17:
>
>>
>> For $thing[-1] I think this only works for strings (and I have this
>> implemented, should probably RFC it) https://github.com/lt/php-src/
>> tree/string_negative_offset
>>
>> $thing[-1:] is in scope for arrays though
>>
>>
> Why? Getting the last value of an array is just as useful as getting the
> last character of a string.
>
> It doesn't work *with that syntax*, because -1 is a valid key, just as
> $thing[0] can't mean "first value of array" because it already means "value
> with key 0". That's why I propose a new syntax such as $thing[@0],
> $thing[@-1], etc.
>
> Regards,
> --
> Rowan Collins
> [IMSoP]
>


Re: [PHP-DEV] RFC Karma

2015-03-20 Thread Alex Bowers
Grand.

Thank you.

On 20 March 2015 at 19:00, Ferenc Kovacs  wrote:

>
> On Fri, Mar 20, 2015 at 2:56 PM, Alex Bowers  wrote:
>
>> Good day,
>>
>> My Wiki username is: alexbowers
>>
>> I have an RFC currently under gauge within the thread (link:
>> https://marc.info/?l=php-internals&m=142679821024794&w=2 )
>>
>> Which seems to be getting some positive reviews, and so I would like to
>> write an official RFC to be placed into discussion.
>>
>> Thanks,
>> Alex.
>>
>
> done
>
> --
> Ferenc Kovács
> @Tyr43l - http://tyrael.hu
>


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
>
> That's why I propose a new syntax such as $thing[@0], $thing[@-1]


I have to agree that a new syntax will be required by this.

On 20 March 2015 at 18:17, Rowan Collins  wrote:

> Leigh wrote on 20/03/2015 16:17:
>
>>
>> For $thing[-1] I think this only works for strings (and I have this
>> implemented, should probably RFC it) https://github.com/lt/php-src/
>> tree/string_negative_offset
>>
>> $thing[-1:] is in scope for arrays though
>>
>>
> Why? Getting the last value of an array is just as useful as getting the
> last character of a string.
>
> It doesn't work *with that syntax*, because -1 is a valid key, just as
> $thing[0] can't mean "first value of array" because it already means "value
> with key 0". That's why I propose a new syntax such as $thing[@0],
> $thing[@-1], etc.
>
> Regards,
> --
> Rowan Collins
> [IMSoP]
>


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
>
> Yes, I'm very conscious of the substantial BC break, which is why I would

target PHP 8 (or even 9, following a deprecation cycle).


I would guess PHP 8, since you can deprecate things at 7.x

Either way, if you make this a separate thread so we don't get off topic,
and i'm sure you'll get many responses from people who want to have their
say.


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
When you say restrict to one each. Do you mean one for strings and one for
arrays?

If so I'd have to disagree with this, since having the same operation
available to both is less likely to give mistakes. Can you give an example
of an actual benefit for this? Since this would cause a backwards
incompatible change. I can't imagine many places if any use the curly
brackets for arrays or strings, but since it exists there may be people
using it. Changing the behaviour of this to only work for one of the two
options seems unnecessary in the name of making code slightly more apparent
on initial reading. But variable names and so on should be used to help
distinguish from array or strings anyway.
 On 20 Mar 2015 17:02, "Vik Hudec"  wrote:

> Hi Alex,
>
> On Fri, 2015-03-20, at 14:52, Alex Bowers wrote:
>
> > But I don't think we should only match {} for strings and [] for arrays,
> > that seems broken to me.
>
> > Maybe you misunderstand me, I am against using two syntaxes for different
> > things.
>
> Based on your reply; yes, I'm definitely misunderstanding! In summary, we
> already have two different operations:
>
> (1) Accessing an array's element using subscript notation, eg:
> $foo = array('bar'); var_dump($foo[0]); // string(3) "bar"
>
> (2) Accessing a string's character using subscript notation, eg:
> $foo = 'bar'; var_dump($foo[0]); // string(1) "b"
>
> And we already have two different syntaxes: $var[$offset] and
> $var{$offset}.
>
> So we have two syntaxes that each perform two operations. Are we in
> agreement that this isn't a good thing?
>
> Sorry that this is all a little off-topic, but I'm interested in people's
> opinions because I'm considering a future RFC. My proposition would be to
> restrict the two subscript syntaxes to one operation each. And if your
> slice
> sugar RFC aims to augment the functionality of either one or both of these
> syntaxes, then that's relevant to me.
>
> Vik
>
>


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
On 20 March 2015 at 16:17, Leigh  wrote:

> $thing[-1:] is in scope for arrays though


How would this work for slicing?

Since doing [@-1:] would mean get the last element to the end.

And doing [@1:-1] is the exact same as doing [@1:] since -1 and blank both
mean the end.


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
I agree the scope is enough. Going with what Rowan added in about
individual indexes (not slicing) by position to be added in with this,
since the two go together.

In my opinion, the $thing[-1] should be a separate RFC, since it has little
to do with slicing, which is the primary focus of this RFC.

On 20 March 2015 at 16:17, Leigh  wrote:

>
> On Mar 20, 2015 4:00 PM, "Alex Bowers"  wrote:
> >>
> >> IMHO, stick to offsets in the first instance, this is a slice notation,
> first order of business is to make it behave like array_slice (+on
> strings). Assoc key based slicing feels pretty wrong to me at this point.
> >
> >
> > I have to agree, we are getting ahead of ourselves.
> >
> > A quick summary of what this RFC should cover:
> >
> > - Slicing an array or string based on the positional index.
> >
> > Things for future RFC consideration:
> >
> > - Slicing an array or string based on the key.
> > - Index -1 for last item of list.
> >
> > Everybody agree that the only focus of this RFC should be the positional
> index slicing?
>
> I think that's plenty for initial scope, since at this point proposals are
> targeting 7.1 there's plenty of time to get assoc indexing in if there is
> enough support for this in the first instance.
>
> If there is support for positional but not assoc, we don't want this
> proposal to fail on the fact they are bundled together.
>
> Not sure I understand your index -1 line (sorry, on phone in pub, really
> just skimming mails). If you mean negative indices for positions from the
> end of the array/string then +1 for this *with* the slice syntax.
>
> For $thing[-1] I think this only works for strings (and I have this
> implemented, should probably RFC it)
> https://github.com/lt/php-src/tree/string_negative_offset
>
> $thing[-1:] is in scope for arrays though
>


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
>
> I'd be tempted to introduce the ability to get a single element by
> position as well


Absolutely agree.

Can we agree on a symbol do you think, or should the RFC continue for the
symbol discussion?


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
>
> IMHO, stick to offsets in the first instance, this is a slice notation,
> first order of business is to make it behave like array_slice (+on
> strings). Assoc key based slicing feels pretty wrong to me at this point.


I have to agree, we are getting ahead of ourselves.

A quick summary of what this RFC should cover:

- Slicing an array or string based on the positional index.

Things for future RFC consideration:

- Slicing an array or string based on the key.
- Index -1 for last item of list.

Everybody agree that the only focus of this RFC should be the positional
index slicing?


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
>
> So $dictionary['elephant':'snake'] returns all elements with keys which
> sort lexically between 'elephant' and 'snake', regardless of whether the
> array is sorted.


Makes sense to me.

Alternatively, a key-based slice could look up the position in the array of
> the two keys, and then perform a positional slice between those positions,
> i.e. $array[$a:$b] == $array[ @ key_position($array, $a) :
> key_position($array, $b) ]. I'm not sure that's particularly intuitive or
> useful, but again, it has no problem with string keys.


I'd say no to that, since it is not an obvious use case, since if you are
defining associated arrays, going for the indexes of those fields feels
strange; since one of the major benefits to associated keys is that the
order doesn't matter anymore. Having this one feature order dependant
whilst using the associated keys isn't correct in my view.

On 20 March 2015 at 14:41, Rowan Collins  wrote:

> Alex Bowers wrote on 20/03/2015 13:40:
>
>> Still not sure how we can implement a range of strings. But since thats
>> for a different feature, I'll leave that issue for now.
>>
>
> I can't resist a quick answer: if you can define a key-based slice at all,
> you can define it for both integer and string keys. Bear in mind the a:b
> here isn't a range, it's just a pair of values specifying which items to
> include in the slice.
>
> If the definition of a key-based slice is "all elements whose key
> satisfies $key >= $a && $key <= $b", then you're just doing comparisons
> between strings, which are defined as lexical order. So
> $dictionary['elephant':'snake'] returns all elements with keys which sort
> lexically between 'elephant' and 'snake', regardless of whether the array
> is sorted.
>
> Alternatively, a key-based slice could look up the position in the array
> of the two keys, and then perform a positional slice between those
> positions, i.e. $array[$a:$b] == $array[ @ key_position($array, $a) :
> key_position($array, $b) ]. I'm not sure that's particularly intuitive or
> useful, but again, it has no problem with string keys.
>
> Regards,
> --
> Rowan Collins
> [IMSoP]
>


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
>
> Certainly it breaks BC (and would presumably have to wait until PHP 8), but
> if we were starting from scratch today, why would it make sense to have two
> syntaxes that do exactly the same thing?


Maybe you misunderstand me, I am against using two syntaxes for different
things.


[PHP-DEV] RFC Karma

2015-03-20 Thread Alex Bowers
Good day,

My Wiki username is: alexbowers

I have an RFC currently under gauge within the thread (link:
https://marc.info/?l=php-internals&m=142679821024794&w=2 )

Which seems to be getting some positive reviews, and so I would like to
write an official RFC to be placed into discussion.

Thanks,
Alex.


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
Okay,

Still not sure how we can implement a range of strings. But since thats for
a different feature, I'll leave that issue for now.

In the list you provided, all of the ones for positional slicing will
definitely be implemented.

Question: What would be the best name for this feature? I do like *positional
slicing,* but I'm sure there are better names out there. Since it isn't
exclusively array based, and is entirely based on the index position (not
key), positional slicing makes sense, and allows for the future to have key
slicing implemented with their own separate documentation pages provided
and clear naming for the differences between them.

On 20 March 2015 at 13:21, Rowan Collins  wrote:

>  Alex Bowers wrote on 20/03/2015 13:10:
>
> $array['x':'z'] = []; // Remove all elements with keys between 'x' and
>> 'z', inclusive
>
>
>  I believe i mentioned in the past about strings not being allowed for
> ranges, since there is no real way to check this (and this appears to be by
> key not by index) which should be a separate RFC thread, assuming this one
> gets accepted to be expanded upon.
>
>
> I'm carrying over my syntax from previous examples - [a:b] meaning a
> key-based slice (which implies accepting string keys, because there's no
> reason not to) vs [@a:b] meaning a positional slice. See my earlier mail on
> the 6 different types of access - I do realise you're not planning to
> implement them all, just playing with the implications of different
> decisions if we carry them through consistently in the future.
>
> Regards,
> --
> Rowan Collins
> [IMSoP]
>


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
>
> It's an alternative syntax


Learn something new every day.

I guess this RFC will need to support both then for consistency reasons; so
it will be down to the end user to determine how they want to separate them
if they choose to. But I don't think we should only match {} for strings
and [] for arrays, that seems broken to me.


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
>
> $array['x':'z'] = []; // Remove all elements with keys between 'x' and
> 'z', inclusive


I believe i mentioned in the past about strings not being allowed for
ranges, since there is no real way to check this (and this appears to be by
key not by index) which should be a separate RFC thread, assuming this one
gets accepted to be expanded upon.



On 20 March 2015 at 13:04, Rowan Collins  wrote:

> Alex Bowers wrote on 20/03/2015 12:32:
>
>> We also need to consider then the possibility of setting data by position.
>>
>> What should $array[@1:3]  = [1,2,3] do?
>>
>> Should it overwrite the values there, and append any that don't exist, or
>> should it be a parse error?
>>
>>
> Good catch. I guess it could delete the range and replace with the new
> value, regardless of size - then you could remove elements from an array
> with it, too:
>
> $array[@1:3] = []; // Remove the second through fourth element
> $array['x':'z'] = []; // Remove all elements with keys between 'x' and
> 'z', inclusive
>
> Not sure how that compares to other languages with similar syntax.
>
> It would be kind of cool if it applied to string subscripts as well:
>
> $version = 'PHP 5.6.1';
> $version{4:} = '7!';
> echo $version; // 'PHP 7!'
>
> Regards,
> --
> Rowan Collins
> [IMSoP]
>


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
On 20 March 2015 at 13:04, Rowan Collins  wrote:

> $version{4:} = '7!';


I'm sure this is a slight oversight on your end, but just to check. The
change of using {} instead of [] is not because its a string, and is just a
typo / example correct?


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
>
> If your branch is available on github let me know, more than happy work on
> it with you.


I'll publish it tonight (GMT), I'm at work at the moment.

Thanks!


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
We also need to consider then the possibility of setting data by position.

What should $array[@1:3]  = [1,2,3] do?

Should it overwrite the values there, and append any that don't exist, or
should it be a parse error?


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
>
> That said, I'm a little older and wiser than I was then, I'd still be
> interested in looking at this. I'll try and come up with _something_ that
> works over the weekend.


I started on the code last night, but didn't get very far. I got it to
match the T_COLON, but no logic or parsing has been done yet. I am still a
bit shaky on how to implement this, so would definitely appreciate the help


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
>
> I've tried implementing python style slice on both strings and arrays in

the past (I don't seem to have an existing branch with it in any more
> though it seems). The biggest problems I hit were regarding the syntax, the
> functionality itself worked.


If you've got a link to your messaging thread, I'd love to read it. Thanks

Colons caused problems with ternary operators in the lexer, and I had an
> issue with commas too, but I forget what it was. Of course these might have
> been resolvable, but I didn't put too much effort into it.


Could this not be mitigated by adding a new token like T_COLON to be used
to match this use case?


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-20 Thread Alex Bowers
>
> The @ symbol in my examples is not a special marker that is meaningful on
> its own; the parser wouldn't even see it as a separate token. The syntax
> for key access is $array[$key], the syntax for positional access would be
> $array[@$position]; chosen to look similar, but one is not a special case
> of the other.


Ah, I understand you now. Yes I agree that this would be useful then. It
allows us the future possibility of a separate RFC looking into slicing on
keys as mentioned at the bottom of your post.

The syntax needn't be just an extra character, we could invent something
> else, like $array[[$position]], or $array@($position), though I can't
> think of anything I like.


I think for simplicity, we should keep it as $array[], and have a symbol
within it that shows that it is an internal index rather than the key. An
Asterisk (*) is my preference at the moment, though caret also looks
promising.

Here are some examples of how various characters could look

$array[*1:3], $array[*:], $array[*:1], $array[*1:]
$array[@1:3], $array[@:], $array[@:1], $array[@1:]
$array[^1:3], $array[^:], $array[^:1], $array[^1:]
$array[&1:3], $array[&:], $array[&:1], $array[&1:]

The symbol isn't something that can be missing, it's just part of the
> syntax, so this is like saying "what should we do if the closing ] is
> missing?" The answer is, nothing, it's undefined syntax, so it's a parse
> error.


So a parse error currently, and a future RFC can define the terms of using
this normally?

If we go down the route of adding a symbol for by index rather than by key,
then this RFC should also include the normal getting array by key style,
without the colon range operator.

For example:

$array[*1] to get the item that is the second in the list, rather than at
key 1.


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-19 Thread Alex Bowers
>
> I'm not sure why it would duplicate the item like that. My interpretation
> of $array[$start:$end] would be "an array containing all those elements of
> $array with a position more than or equal to $start, but less than or equal
> to $end" ($position >= $start && $position <= $end).
>

I agree with this statement now, I was misinterpreting how I thought it
should work, but reading this; I think you're right. Also, your next point
about the unique array indexes covers it anyway, so it doesn't really
matter regardless.

Check my example again. $countdown[0] refers to the element with key 0, so
> is absolutely not a replacement for $countdown[0:0]. This is the whole
> point of my example.


You're correct, this was my mistake.

I'm not sure what you mean by "something that happens nowhere else" PHP has
> syntax for all sorts of things, using all sorts of symbols. Your own
> suggestion uses the : symbol in a place where it currently can't exist.


What I mean by 'symbol' here, is a prefix to tell it what the context of
its use is; in this case, it is the declaration that we are requiring the
index not the key. As far as I'm aware, and can think of at the moment, PHP
has nothing like a hinter symbol.

The only purpose of this symbol is to tell the user that it is indexes not
keys.

Maybe there should be a symbol to declare that, but i'm not sure. Will
appreciate more comments on this.

If we go the direction of using a symbol, what should be the outcome of the
symbol missing? fatal error, or to try to slice based on the keys?


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-19 Thread Alex Bowers
On 19 March 2015 at 23:23, Rowan Collins  wrote:

> On 19/03/2015 20:49, Alex Bowers wrote:
>
>> My proposal is something similar to Pythons slice, in PHP this would look
>> like:
>>
>> $slided = $array[1:4]
>>
>> This will get the elements in positions 1,2,3,4. (1 through 4 inclusive),
>> ignoring the actual key of the array. The result for an array will be an
>> array with the keys preserved, in the same order.
>>
>
> While I can see the reasoning for not looking into the actual keys (which
> might not have a logically sliceable order), I think the syntax needs to be
> more distinct, because this seems a bit confusing:
>
> $countdown = [ 5 => 'Five!', 4 => 'Four!', 3 => 'Three!', 2 => 'Two!', 1
> => 'One!', 0 => 'Zero!' ]
>
> $countdown[0]; // 'Zero!'
> $countdown[0:0]; // ['Five!']
> $countdown[0:][0] // 'Zero!'
> $countdown[:0][0] // null - slice contains no key 0
>
> The problem is that the slice access looks like an extension of key
> access, but is actually a new concept of positional element access. With a
> slight tweak to syntax, such as adding an @, we could make positional
> access available for non-slices as well:
>
> reset($countdown); // Five! - a common way of getting the first element
> positionally
> $countdown[@0]; // 'Five!'
> $countdown[@1]; // 'Four!'
> $countdown[@0:0] // ['Five!']
> $countdown[@0:1] // ['Five!', 'Four!']
> $countdown[@0:][@0] // 'Five!'
> $countdown[@:0][@0] // 'Five!'
>
>
>  A side addition, that may be considered is adding [-1] to get the last
>> item
>> in the array. But that is not a main part of this RFC.
>>
>
> This would actually be a really important addition for me, but only if I
> can do it on a non-slice, as above:
>
> $countdown[-1]; // null - no such key
> end($countdown); // 'Zero!'  - common way of getting last element
> $countdown[@-1]; // 'Zero!' - positional access counting from the end
> $countdown[@-2]; // 'One!' - fiddly to do in current PHP
>
>
> I just wrote out all those examples and realised that it may not be
> possible to reuse @ in this context. Finding new symbols to use for syntax
> is hard. :(
>
> Regards,
>
> --
> Rowan Collins
> [IMSoP]
>
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>
While I can see the reasoning for not looking into the actual keys (which
> might not have a logically sliceable order), I think the syntax needs to be
> more distinct, because this seems a bit confusing:
> $countdown = [ 5 => 'Five!', 4 => 'Four!', 3 => 'Three!', 2 => 'Two!', 1
> => 'One!', 0 => 'Zero!' ]
> $countdown[0]; // 'Zero!'
> $countdown[0:0]; // ['Five!']
> $countdown[0:][0] // 'Zero!'
> $countdown[:0][0] // null - slice contains no key 0
>

Thats a good point, something else that just came to me; your example of
$countdown[0:0]; if we had it as inclusive indexes, then this would
actually give you ['Five!', 'Five!'], which is unlikely to be what was
desired. What would be a good solution to this?

1) The range cannot be 0 in length (such that, from - to must be > 0) -
This would also get around issues of people trying to use it like so :
$countdown[5:3], as the expected outcome of that should be a fatal error.
Also, your use-case of 0:0 would be better placed simply using
$countdown[0].

The issue with this solution would then come that  if there was any code
for this range being dynamic, some logic would have to take place on the
users side to ensure that $from and $to differ by at least +1

To me, this isn't really a big issue, since I cannot see this being that
big of a use case, but it is worth mentioning.

To me, a larger use case would be a user wanting say, the first N items
from an array, and so using $sub_array = $array[: (N-1)], which can then be
easily used within a foreach loop, without the need for $key to be used and
breaking out of the foreach loop on the Nth iteration.

The problem is that the slice access looks like an extension of key access,
> but is actually a new concept of positional element access. With a slight
> tweak to syntax, such as adding an @, we could make positional access
> available for non-slices as well:


I think the use of the @ symbol would be misplaced for this; it already has
a meaning within PHP, and many people are often taught to shy away from it
(due to previous bad coding practices using it heavily); and so this

Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-19 Thread Alex Bowers
On 19 March 2015 at 21:11, Larry Garfield  wrote:

> On 3/19/15 4:06 PM, Alex Bowers wrote:
>
>> I've had a quick scan of the list at https://wiki.php.net/rfc but cannot
>> seem to find anything. I'll read more carefully through, or is there a
>> different list elsewhere which I should look at?
>>
>
> Not everything makes it to an RFC.  This list's archives are quite
> extensive.  (People here are verbose):
>
> http://php.net/mailing-lists.php
> http://marc.info/?l=php-internals
>
> Also, no top-posting, please.
>
> --Larry Garfield
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>
Apologies about the top post, that was gmail automatically hiding the main
content so I just typed. Thanks for the links. I will look through them now
to find some proposals which have failed before; and try to improve this
one. Still would like feedback from anybody else reading this too. Thanks.


Re: [PHP-DEV] RFC - Array slice syntactic sugar

2015-03-19 Thread Alex Bowers
I've had a quick scan of the list at https://wiki.php.net/rfc but cannot
seem to find anything. I'll read more carefully through, or is there a
different list elsewhere which I should look at?


On 19 March 2015 at 21:03, Larry Garfield  wrote:

> On 3/19/15 3:49 PM, Alex Bowers wrote:
>
>> This email is just to gauge the response for some syntactic sugar to be
>> added to PHP in regard to slicing an array.
>>
>> My proposal is something similar to Pythons slice, in PHP this would look
>> like:
>>
>> $slided = $array[1:4]
>>
>> This will get the elements in positions 1,2,3,4. (1 through 4 inclusive),
>> ignoring the actual key of the array. The result for an array will be an
>> array with the keys preserved, in the same order. Any multi-dimensions are
>> also respected and returned within the array.
>>
>> This is the same as using the array_slice method with the PRESERVE KEYS
>> fourth parameter passed through as true.
>>
>> The result for a string is the string from the two positions indicated.
>> This is the same as using substr().
>>
>> The benefits for this as I see it is:
>>
>> 1) No function overhead
>> 2) More readable (opinionated)
>> 3) Consistent with how we can select items from an array currently (using
>> index).
>>
>> If the array is not long enough (for example, index 4 doesn't exist), then
>> a NOTICE is thrown, and the values returned are as much as possible; this
>> would be the same as calling $array[1:] which will get the items in
>> position 1 through to the end.
>>
>> If the variable used contains a string, then this will get the values from
>> the string at those positions. The same way that $string[1] will get the
>> second character, $string[2:5] will get the third through to the sixth
>> character. This differs from array_slice which would throw a warning and
>> return null.
>>
>> If the variable isn't either a string or an array (or convertible to
>> either); then a warning is thrown and null is returned, consistent with
>> current use ($int[0] will return null)
>>
>> Arrays with associated keys cannot be selected by using the keys they
>> have,
>> but instead should be selected by the position those keys hold.
>>
>> For example, this is invalid:
>>
>> $array['string':'end']. This should throw a fatal error.
>>
>> The valid options are:
>>
>> $array[from:to] - This gets the values from position 'from' to 'to'
>> inclusive
>> $array[from:] - This gets the values from the position 'from' to the end.
>> $array[:to] - This gets the values from the start to the position 'to'.
>>
>> $array[:] will get all the items in the array ($same as doing $array)
>>
>> A side addition, that may be considered is adding [-1] to get the last
>> item
>> in the array. But that is not a main part of this RFC.
>>
>> Thanks
>>
>
>
> Variations of this proposal have been discussed many times.  I don't
> recall what the pushback was but it's worth your time to check the archives
> to see what the objections were and if you can address them, and/or if the
> new engine in PHP 7 addresses them.  (I suspect it has/will ameliorate a
> lot of implementation-level issues with old proposals.)
>
> Personally I'd be in favor of such a syntax but I don't recall the
> objections in the past beyond "meh, sugar".
>
> --Larry Garfield
>
> --
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>


[PHP-DEV] RFC - Array slice syntactic sugar

2015-03-19 Thread Alex Bowers
This email is just to gauge the response for some syntactic sugar to be
added to PHP in regard to slicing an array.

My proposal is something similar to Pythons slice, in PHP this would look
like:

$slided = $array[1:4]

This will get the elements in positions 1,2,3,4. (1 through 4 inclusive),
ignoring the actual key of the array. The result for an array will be an
array with the keys preserved, in the same order. Any multi-dimensions are
also respected and returned within the array.

This is the same as using the array_slice method with the PRESERVE KEYS
fourth parameter passed through as true.

The result for a string is the string from the two positions indicated.
This is the same as using substr().

The benefits for this as I see it is:

1) No function overhead
2) More readable (opinionated)
3) Consistent with how we can select items from an array currently (using
index).

If the array is not long enough (for example, index 4 doesn't exist), then
a NOTICE is thrown, and the values returned are as much as possible; this
would be the same as calling $array[1:] which will get the items in
position 1 through to the end.

If the variable used contains a string, then this will get the values from
the string at those positions. The same way that $string[1] will get the
second character, $string[2:5] will get the third through to the sixth
character. This differs from array_slice which would throw a warning and
return null.

If the variable isn't either a string or an array (or convertible to
either); then a warning is thrown and null is returned, consistent with
current use ($int[0] will return null)

Arrays with associated keys cannot be selected by using the keys they have,
but instead should be selected by the position those keys hold.

For example, this is invalid:

$array['string':'end']. This should throw a fatal error.

The valid options are:

$array[from:to] - This gets the values from position 'from' to 'to'
inclusive
$array[from:] - This gets the values from the position 'from' to the end.
$array[:to] - This gets the values from the start to the position 'to'.

$array[:] will get all the items in the array ($same as doing $array)

A side addition, that may be considered is adding [-1] to get the last item
in the array. But that is not a main part of this RFC.

Thanks