Php array обратная сортировка

PHP array_reverse

Summary: in this tutorial, you will learn how to use the PHP array_reverse() function to reverse the order of elements in an array.

Introduction to the PHP array_reverse() function

The array_reverse() function accepts an array and returns a new array with the order of elements in the input array reversed.

The following shows the array_reverse() function:

array_reverse ( array $array , bool $preserve_keys = false ) : arrayCode language: PHP (php)

The array_reverse() function has two parameters:

  • $array is the input array
  • $preserve_keys determines if the numeric keys should be preserved. If $preserve_keys is true , the numeric key of elements in the new array will be preserved. The $preserve_keys doesn’t affect the non-numeric keys.

The array_reverse() doesn’t change the input array. Instead, it returns a new array.

PHP array_reverse() function examples

Let’s take some examples of using the PHP array_reverse() function.

Читайте также:  Str to date java

1) Simple PHP array_reverse() function example

The following example uses the array_reverse() function to reverse the order of an array:

 $numbers = [10, 20, 30]; $reversed = array_reverse($numbers); print_r($reversed); print_r($numbers);Code language: HTML, XML (xml)
Array ( [0] => 30 [1] => 20 [2] => 10 ) Array ( [0] => 10 [1] => 20 [2] => 30 )Code language: plaintext (plaintext)
  • First, define an array of three numbers 10, 20, 30.
  • Then, use the array_reverse() function to create a new array with the order of elements in the $numbers array reversed.
  • Finally, show the reversed array and the $numbers array. As you can see, the $numbers array doesn’t change.

2) Using the PHP array_reverse() function to preserve numeric keys

The following example uses the array_reverse() function to reverse elements of an array. However, it preserves the keys of the elements:

 $book = [ 'PHP Awesome', 999, ['Programming', 'Web development'], ]; $preserved = array_reverse($book, true); print_r($preserved);Code language: HTML, XML (xml)
Array ( [2] => Array ( [0] => Programming [1] => Web development ) [1] => 999 [0] => PHP Awesome )Code language: PHP (php)

Summary

  • Use the PHP array_reverse() function to reverse the order of elements in an array.
  • Set the $preserve_keys to true to preserve the keys in the original array.

Источник

array_reverse

Принимает массив array и возвращает новый массив, содержащий элементы исходного массива в обратном порядке.

Список параметров

Если установлено в true , то числовые ключи будут сохранены. Нечисловые ключи не подвержены этой опции и всегда сохраняются.

Возвращаемые значения

Возвращает массив с элементами в обратном порядке.

Примеры

Пример #1 Пример использования array_reverse()

$input = array( «php» , 4.0 , array( «green» , «red» ));
$reversed = array_reverse ( $input );
$preserved = array_reverse ( $input , true );

print_r ( $input );
print_r ( $reversed );
print_r ( $preserved );
?>

Результат выполнения данного примера:

Array ( [0] => php [1] => 4 [2] => Array ( [0] => green [1] => red ) ) Array ( [0] => Array ( [0] => green [1] => red ) [1] => 4 [2] => php ) Array ( [2] => Array ( [0] => green [1] => red ) [1] => 4 [0] => php )

Смотрите также

User Contributed Notes

  • Функции для работы с массивами
    • array_​change_​key_​case
    • array_​chunk
    • array_​column
    • array_​combine
    • array_​count_​values
    • array_​diff_​assoc
    • array_​diff_​key
    • array_​diff_​uassoc
    • array_​diff_​ukey
    • array_​diff
    • array_​fill_​keys
    • array_​fill
    • array_​filter
    • array_​flip
    • array_​intersect_​assoc
    • array_​intersect_​key
    • array_​intersect_​uassoc
    • array_​intersect_​ukey
    • array_​intersect
    • array_​is_​list
    • array_​key_​exists
    • array_​key_​first
    • array_​key_​last
    • array_​keys
    • array_​map
    • array_​merge_​recursive
    • array_​merge
    • array_​multisort
    • array_​pad
    • array_​pop
    • array_​product
    • array_​push
    • array_​rand
    • array_​reduce
    • array_​replace_​recursive
    • array_​replace
    • array_​reverse
    • array_​search
    • array_​shift
    • array_​slice
    • array_​splice
    • array_​sum
    • array_​udiff_​assoc
    • array_​udiff_​uassoc
    • array_​udiff
    • array_​uintersect_​assoc
    • array_​uintersect_​uassoc
    • array_​uintersect
    • array_​unique
    • array_​unshift
    • array_​values
    • array_​walk_​recursive
    • array_​walk
    • array
    • arsort
    • asort
    • compact
    • count
    • current
    • end
    • extract
    • in_​array
    • key_​exists
    • key
    • krsort
    • ksort
    • list
    • natcasesort
    • natsort
    • next
    • pos
    • prev
    • range
    • reset
    • rsort
    • shuffle
    • sizeof
    • sort
    • uasort
    • uksort
    • usort
    • each

    Источник

    PHP: array_reverse() function

    PHP: Create an array with elements in reverse order

    The array_reverse() function is used to reverse the order of the elements in an array.

    array_reverse(array_name, preserve_keys)
    Name Description Required /
    Optional
    Type
    array_name Specifies the name of the array. Required Array
    preserve_keys Specify TRUE or FALSE whether function shall preserve the array’s keys or not. The default value is FALSE. Optional Boolean

    Return value:

    Value Type: Array

    Array ([4] => 5 [3] => 4 [2] => 3 [1] => 2 [0] => 1) 
    Array ([0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1)

    Pictorial Presentation:

    php function reference: array_reverse() function

    Practice here online :

    Previous: array_reduce
    Next: array_search

    Follow us on Facebook and Twitter for latest update.

    PHP: Tips of the Day

    How can I sanitize user input with PHP?

    It’s a common misconception that user input can be filtered. PHP even has a (now deprecated) «feature», called magic-quotes, that builds on this idea. It’s nonsense. Forget about filtering (or cleaning, or whatever people call it).

    What you should do, to avoid problems, is quite simple: whenever you embed a string within foreign code, you must escape it, according to the rules of that language. For example, if you embed a string in some SQL targeting MySQL, you must escape the string with MySQL’s function for this purpose (mysqli_real_escape_string). (Or, in case of databases, using prepared statements are a better approach, when possible.)

    Another example is HTML: If you embed strings within HTML markup, you must escape it with htmlspecialchars. This means that every single echo or print statement should use htmlspecialchars.

    A third example could be shell commands: If you are going to embed strings (such as arguments) to external commands, and call them with exec, then you must use escapeshellcmd and escapeshellarg.

    The only case where you need to actively filter data, is if you’re accepting preformatted input. For example, if you let your users post HTML markup, that you plan to display on the site. However, you should be wise to avoid this at all cost, since no matter how well you filter it, it will always be a potential security hole.

    • Weekly Trends
    • Java Basic Programming Exercises
    • SQL Subqueries
    • Adventureworks Database Exercises
    • C# Sharp Basic Exercises
    • SQL COUNT() with distinct
    • JavaScript String Exercises
    • JavaScript HTML Form Validation
    • Java Collection Exercises
    • SQL COUNT() function
    • SQL Inner Join
    • JavaScript functions Exercises
    • Python Tutorial
    • Python Array Exercises
    • SQL Cross Join
    • C# Sharp Array Exercises

    We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

    Источник

    PHP array_reverse() Function

    The array_reverse() function returns an array in the reverse order.

    Syntax

    Parameter Values

    Technical Details

    Return Value: Returns the reversed array
    PHP Version: 4+
    PHP Changelog: The preserve parameter was added in PHP 4.0.3

    More Examples

    Example

    Return the original array, the reversed array and the preserved array:

    Unlock Full Access 50% off

    COLOR PICKER

    colorpicker

    Join our Bootcamp!

    Report Error

    If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

    Thank You For Helping Us!

    Your message has been sent to W3Schools.

    Top Tutorials
    Top References
    Top Examples
    Get Certified

    W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

    Источник

    How to Use array_reverse() Function in PHP

    While working with arrays in PHP, we may need to reverse the order of an array. For this, we have a predefined PHP function called array_reverse(). This function allows us to reverse the order of any input array. This article covers the array_reverse() function in detail, including its syntax, parameters, and example codes.

    What is the array_reverse() Function in PHP?

    The array_reverse() function can reverse or reorder the array elements. This function takes an array as its input and returns a new array with the order of the elements reversed.

    Syntax

    The syntax for the array_reverse() function is as follows:

    The function takes an array as its first argument and an optional Boolean value as its second argument. If the second parameter preserve_keys is set to TRUE, the function will preserve the keys of the array. If the second parameter is not set or set to FALSE, the function will reset the keys of the array. By default, a FALSE value is assigned to this parameter.

    Parameter

    The array_reverse() function takes two parameters:

    • Array: The array to be reversed. This is a required parameter.
    • preserve_keys: An optional Boolean value that determines whether to preserve the keys of the array or not. It is set to FALSE by default.

    Return

    A reversed array is returned by array_reverse() function.

    Example 1: Reversing an Array

    In the code given below, we will create an array of numbers and then use the array_reverse() function to reverse the order of the elements in the array without preserving the keys:

    $numbers = array ( 1 , 2 , 3 , 4 , 5 ) ;
    $reversed_numbers = array_reverse ( $numbers ) ;
    print_r ( $reversed_numbers ) ;
    ?>

    Output
    In the output, we can see the array_reverse() function has reversed the order of the elements in the array without preserving the keys:

    Example 2: Reversing an Array and Preserving Keys

    Now we will create an array of strings and then using the array_reverse() function we will reverse the order of the elements in the array while preserving the keys:

    $numbers = array ( 1 , 2 , 3 , 4 , 5 ) ;
    $reversed_numbers = array_reverse ( $numbers , True ) ;
    print_r ( $reversed_numbers ) ;
    ?>

    Output
    Here, the array_reverse() function has reversed the order of the elements in the array while preserving the keys:

    Example 3: Reversing a Multidimensional Array

    In the code below we have created a multidimensional array and then using the array_reverse() we will reverse the order of array elements:

    $animals = array (
    array ( ‘name’ => ‘dog’ , ‘color’ => ‘brown’ ) ,
    array ( ‘name’ => ‘cat’ , ‘color’ => ‘gray’ ) ,
    array ( ‘name’ => ‘bird’ , ‘color’ => ‘blue’ )
    ) ;
    $reversed_animals = array_reverse ( $animals ) ;
    print_r ( $reversed_animals ) ;
    ?>

    Output
    In the output, we can see the array_reverse() function has reversed the order of elements present inside a multidimensional array:

    Array (
    [ 0 ] => Array ( [ name ] => bird [ color ] => blue )
    [ 1 ] => Array ( [ name ] => cat [ color ] => gray )
    [ 2 ] => Array ( [ name ] => dog [ color ] => brown )
    )

    Conclusion

    With array_reverse() in PHP, we can reorder the elements of an array. A new array is returned by this function, with the elements rearranged according to the input array. This article covers the details of array_reverse() function. For a complete description of the syntax, parameters, and return value of this function read the article.

    About the author

    Kashif

    I am an Electrical Engineer. I love to write about electronics. I am passionate about writing and sharing new ideas related to emerging technologies in the field of electronics.

    Источник

Оцените статью