Please, let me know if this is the specification for search()
of Laravel Prompts,
and let me know if my thoughts are correct.
0.1.17
search()
search()
returns:
This is written in value()
method of Laravel\Prompts\SearchPrompt
return array_is_list($this->matches)
? $this->matches[$this->highlighted]
: array_keys($this->matches)[$this->highlighted];
When expecting the selected value of the array to be returned, an index may be returned in cases.
For example, the code below using list:
$data = ['foo', 'bar', 'baz'];
echo search(
label: 'Input User Name',
options: fn ($value) => strlen($value) > 0
? array_filter($data, fn ($e) => str_contains($e, $value))
: [],
) . "\n";
results in as follows.
It returns foo
if selected foo
after searching f
.
It returns 1
if selected bar
after searching b
.
CASE 1
, the array of search result [0 => 'foo']
is a list.CASE 2
, the array of search result [1 => 'bar', 2 => 'baz']
is not a list.This occurs because the returned array byarray_filter()
keeps the original array indices, and [1 => 'bar', 2 => 'baz']
is treated like hash.
I know wrapping array_filter()
in array_values()
can avoid this issue from occurring.
$data = ['foo', 'bar', 'baz'];
echo search(
label: 'Input User Name',
options: fn ($value) => strlen($value) > 0
? array_values(array_filter($data, fn ($e) => str_contains($e, $value)))
: [],
) . "\n";
And I've checked the issue #119.
This behavior of search()
is the specification and not a bug.
And I must always set list (array with zero-started indices) as options
if I want to get the selected value of the array.
Are these right?
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community