Marc Wampfler
Marc Wampfler

Reputation: 159

PHP function is not available in my current PHP Version

I would like to use the function array_key_first (PHP 7 >= 7.3.0).

My current PHP Version is 7.2

I use the "Polyfill" as described within the "User Contributed Notes" section of corresponding PHP manual

If I call the array_key_first function in my index.php which is where the polyfill is, everything works fine.

If I call the array_key_first function within a PHP self-written class, it doesn't work.

How can I define "Polyfills" so that they are "globally" available?

I don't want to define a class method an call it with $this->array_key_first...

I include the following code in my index.php file

    if (!function_exists('array_key_first')) {
        function array_key_first(array $array){
            if (count($array)) {
                reset($array);
                return key($array);
            }
            return null;
        }
    }

Thanks for hints

Upvotes: 6

Views: 8322

Answers (3)

xate
xate

Reputation: 6379

You can just call key()[1] on the array to retrieve the first key, assuming that the array pointer is currently pointing at the first element, otherwise you would have to call reset()[2] on it before, e.g:

$array = ['a' => 1, 'b' => 2];
var_dump(key($array));

or

$array = ['a' => 1, 'b' => 2];
reset($array);
var_dump(key($array));

https://3v4l.org/ELdhf

string(1) "a"

Upvotes: 0

Andreas
Andreas

Reputation: 23958

I believe you can use array_keys for this.
Array_keys will get all keys in order where [0] is the first.

$arr = ["m" => 0,"b" => 1, "k"  => 2,"a" => 3];
$key = array_keys($arr)[0];

echo $key; //m

If we look at this example you see that array_keys does not change the position in the array.

It echoes 0 first which is key 0.
Then I move it one step and it echo 1.
Then we do array keys and check again what the position is and it's still 1.
https://3v4l.org/bhoEZ

Upvotes: 7

Alister Bulman
Alister Bulman

Reputation: 35169

If you aren't using a composer-based workflow for including files (which can include files automatically when you first require the autoload.php file), there will only be two ways.

  1. Include a file manually to define the function wherever it is used
  2. change the php.ini file to 'prepend' a file (include a PHP file before the main script runs)

    auto_prepend_file="/path/to/polyfill.php"

If you are on shared hosting, it is unlikely you will be able to change the php.ini file though.

The polyfill defines the function like this:

 function array_key_first(array $array) { foreach ($array as $key => $value) { return $key; } }

Upvotes: 1

Related Questions