0

I was reading some Wordpress plugin code when I come across this function:

function bp_nouveau_hook( $pieces = array() ) {
    if ( ! $pieces ) {
        return;
    }
 
    $bp_prefix = reset( $pieces );
    if ( 'bp' !== $bp_prefix ) {
        array_unshift( $pieces, 'bp' );
    }
 
    $hook = join( '_', $pieces );
 
    /**
     * Fires inside the `bp_nouveau_hook()` function.
     *
     * @since BuddyPress 3.0.0
     */
    do_action( $hook );
}

As far as I understand you use reset() when the array's pointer could be changed by functions such as prev() or next() etc. But by reading this code, I don't see any chance the $pieces array parameter's pointer could be changed. Why then use reset() here?

shenkwen
  • 3,536
  • 5
  • 45
  • 85
  • 1
    Perhaps to make sure it hasn't been changed before it enters the function? – aynber Jan 21 '22 at 19:32
  • 2
    If `$pieces` is not a 0-based indexed array, `reset()` is the only reliable way to get the *first* item from the array. – rickdenhaan Jan 21 '22 at 19:32
  • That's exactly it. The array pointer is copied when passing an array to a function. – Barmar Jan 21 '22 at 19:33
  • Related: https://stackoverflow.com/questions/1617157/how-to-get-the-first-item-from-an-associative-php-array/46443841 – k0pernikus Jan 21 '22 at 19:37
  • image you have an array `['some' => 'value', 'another' => 'one']`, how could you get the first item in this array if you do not know beforehand what the values of the keys are? By using `reset` you will get the first value no matter the keys. – Dirk J. Faber Jan 21 '22 at 21:17

1 Answers1

0

As per the docs reset:

Returns the value of the first array element, or false if the array is empty.

The reset is done to get the first element of the array.

k0pernikus
  • 60,309
  • 67
  • 216
  • 347
  • @Barmar The array might not have numeric keys. Hence reset is a way to get the first item. That is why it is used here: to get the first item. – k0pernikus Jan 21 '22 at 19:36