Php массив обратном порядке

PHP array_reverse() Function

The array parameter is required, and it describes the array.

It is an optional parameter specifying whether the function should preserve the array’s keys. Possible values:

Return value

It returns the reversed array.

Example 1: Single-Dimensional Array Reverse in PHP

To reverse a single-dimensional array in PHP, use the array_reverse() function.

  $testArray = array(11, 21, 19, 46, 29); $reverseArray = array_reverse($testArray); print_r($reverseArray);
Array ( [0] => 29 [1] => 46 [2] => 19 [3] => 21 [4] => 11 ) 

Example 2 Reverse Associative Array in PHP

To reverse an associative array in PHP, use the “array_reverse()” function.

 $arr = array("Eleven"=>"Millie", "Mike"=>"Finn", "Dustin"=>"Gaten"); print_r(array_reverse($arr)); 
Array ( [Dustin] => Gaten [Mike] => Finn [Eleven] => Millie )

The next program reverses an array taking the $key_preserve as FALSE by default. This doesn’t preserve the keys.

 $arr = array("Netflix"=>"Marianne", "Movie"=>"Valek", "Bollywood"=>"Daayan"); $rev = array_reverse($arr, FALSE); print_r($rev);
Array ( [Bollywood] => Daayan [Movie] => Valek [Netflix] => Marianne )

Nested Array Reverse in PHP

To reverse a nested array in PHP, use the “array_reverse()” function.

  $testArray = array( 'books' => array( array('name' => 'Game Of Thrones', 'Author' => 'George RR Martin'), array('name' => 'Hunger Games', 'Author' => 'Suzanne Collins'), array('name' => 'Harry Potter', 'Author' => 'JK Rowling') ), 'movies' => array('Hunger Games', 'Harry Potter')); $reverseArray = array_reverse($testArray); print_r($reverseArray); 
( [movies] => Array ( [0] => Hunger Games [1] => Harry Potter ) [books] => Array ( [0] => Array ( [name] => Game Of Thrones [Author] => George RR Martin ) [1] => Array ( [name] => Hunger Games [Author] => Suzanne Collins ) [2] => Array ( [name] => Harry Potter [Author] => JK Rowling ) ) )

Notice that a function reverses an outer array in the nested array above. However, it does not reverse the inner keys of the multidimensional array, as shown.

Источник

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: Обратный (реверсированный) массив в PHP

    В этом уроке мы хотели бы поделиться с вами тем, как инвертировать одномерный массив, ассоциативный массив и многомерный массив в PHP.

    В этом руководстве также показан простой способ реверсирования массива в PHP без функции и реверсирования числового массива в PHP.

    Определение: Функция PHP array_reverse() — это встроенная функция PHP, которая используется для реверсирования элементов или элементов массива.

    Синтаксис: Синтаксис функции array_reverse() следующий.

    array_reverse(array, preserve)

    Параметры функции реверса массива:

    Функция принимает два параметра: первый — массив, а второй — сохранение (TRUE/FALSE).

    • array: параметр массива является обязательным и описывает массив.
    • preserve: — это второй параметр этой функции, и это необязательный параметр. Он указывает, должна ли функция сохранять ключи массива или нет. Возможные значения: true, false.

    Давайте возьмем примеры функции array_reverse():

    1. Обратный одномерный массив в PHP

    Здесь мы возьмем пример с функцией PHP array_reverse(). У нас есть один числовой массив, он содержит в себе числовые значения. Мы перевернем массив, используя функцию реверса массива:

    См. приведенный ниже пример. Этот пример перевернет заданный массив:

    Вывод приведенного выше кода

    Array ( [0] => 49 [1] => 50 [2] => 18 [3] => 12 [4] => 5 )

    2. Обратный ассоциативный массив в PHP

    Здесь мы возьмем пример с ассоциативным массивом в PHP. У нас есть один ассоциативный массив, он содержит в себе значения в паре ключ-значение. Мы перевернем массив, используя функцию реверса массива:

    См. приведенный ниже пример. Этот пример перевернет заданный массив:

    "PHP","b"=>"JAVA","c"=>".NET"); $resKeyValueArray = array_reverse($keyValueArray); print_r($resKeyValueArray); ?>

    Вывод приведенного выше кода

    Array ( [c] => .NET [b] => JAVA [a] => PHP )

    3. Обратный многомерный массив PHP

    Давайте возьмем новый пример с многомерным массивом. У нас есть один многомерный массив, и мы перевернем значения или элементы этого массива, используя функцию array_reverse().

    "PHP","b"=>"JAVA","c"=>".NET"), array("d"=>"jаvascript","e"=>"c","f"=>"c#"), ); $reverseArray = array_reverse($array); print_r($reverseArray); ?> 

    Вывод приведенного выше кода:

    Array ( [0] => Array ( [d] => jаvascript [e] => c [f] => c# ) [1] => Array ( [a] => PHP [b] => JAVA [c] => .NET ) )

    Как перевернуть массив в PHP без функции?

    Вы можете использовать цикл for и функцию PHP unset() для обратного массива без использования функции в PHP.

    Вывод приведенного выше кода:

    Array ( [6] => f [7] => e [8] => d [9] => c [10] => b [11] => a )

    Новость отредактировал: MakeCodes — 21-07-2022, 03:48

    Источник

    How To Reverse Array In PHP

    Reversing an array is a common operation in PHP, and there are several methods available to achieve it. Reversing an array essentially means changing the order of its elements so that the last element becomes the first, the second-to-last element becomes the second, and so on. This can be useful for a variety of purposes, such as displaying the elements of an array in reverse order, or implementing certain algorithms that require the elements of an array to be processed in reverse order.

    One of the simplest and most efficient methods to reverse an array in PHP is by using the array_reverse() function. This function takes an array as input and returns a new array with the elements in reverse order. Another method involves using a for loop to iterate over the original array in reverse order and adding each element to a new array. Alternatively, the array_unshift() function can be used to insert the elements of the original array at the beginning of a new array in reverse order.

    Each of these methods has its own advantages and disadvantages, and the choice of method depends on the specific needs of the project. It is important to carefully consider the performance, readability, and maintainability of the code when selecting a method to reverse an array in PHP. With the right approach, reversing an array can be a simple and straightforward operation that allows you to process and manipulate arrays with ease.

    How To Reverse Array In PHP

    • Method 1: Using the array_reverse() Function
    • Method 2: Using a For Loop
    • Method 3: Using the array_unshift() Function

    Method 1: Using the array_reverse() Function

    The simplest way to reverse an array in PHP is by using the built-in array_reverse() function. This function accepts an array as an argument and returns a new array with the elements in reverse order.

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

    As you can see, the array_reverse() function returns a new array with the elements in reverse order.

    Method 2: Using a For Loop

    Another way to reverse an array in PHP is by using a for loop. This method involves creating a new array and iterating over the original array in reverse order, adding each element to the new array.

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

    In this example, you first create an empty array $reversed . Then, you iterate over the original array $numbers in reverse order using a for loop. For each iteration, you add the current element to the $reversed array using the array [] syntax. Finally, you print the $reversed array using the print_r() function.

    Method 3: Using the array_unshift() Function

    A third method to reverse an array in PHP is by using the array_unshift() function. This function accepts an array as the first argument and one or more values as the remaining arguments. The function inserts the specified values at the beginning of the array, effectively reversing the order of elements.

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

    In this example, you first create an empty array $reversed . Then, you iterate over the original array $numbers using a foreach loop. For each iteration, you insert the current element at the beginning of the $reversed array using the array_unshift() function. Finally, you print the $reversed array using the print_r() function.

    Conclusion

    In this article, you have learned three different methods to reverse an array in PHP.

    Источник

    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.

    Источник

    Читайте также:  Задать двумерный массив си шарп
Оцените статью