Support the ongoing development of Laravel.io →
Laravel Packages

Please, let me know if this is the specification for search() of Laravel Prompts, and let me know if my thoughts are correct.

Laravel Prompts Version

0.1.17

Behavior of search()

search() returns:

  • the value of the array (it the array is a list[array with zero-started indices])
  • the key of the array (if the array is not a lsit)

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];

The Issue

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.

CASE 1:

It returns foo if selected foo after searching f.

CASE 2:

It returns 1 if selected bar after searching b.

The Reason Why This Issue Occurs

  • In CASE 1, the array of search result [0 => 'foo'] is a list.
  • In 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.

My Thoughts

  • 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?

0

Sign in to participate in this thread!

PHPverse

Your banner here too?

macocci7 macocci7 Joined 9 Apr 2024

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.