Created
May 15, 2016 13:25
-
-
Save insideone/93efb2380000dd75da8aabdcec2dbc2d to your computer and use it in GitHub Desktop.
PHP: array_num_flip
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Меняет местами значения и ключи для не-ассоциативных ключей | |
* @param array $ar Входной массив | |
* @param bool $keepValue Оставить ли в качестве значений перевернутой части числовые ключи? | |
* @param string $replacementValue Если $keepValue = false, то данный параметр задаёт новые значения для перевернутой части массива | |
* return array Выходной массив | |
*/ | |
function array_num_flip($ar, $keepValue = false, $replacementValue = '') | |
{ | |
$ar = (array)$ar; | |
$arAssoc = array_intersect_key($ar, array_flip(array_filter(array_keys($ar), 'is_string'))); | |
$arNumoc = array_diff($ar, $arAssoc); | |
return $arAssoc + ( | |
$keepValue || count($arNumoc) === 0 | |
? array_flip($arNumoc) | |
: array_combine($arNumoc, array_fill(0, count($arNumoc), $replacementValue)) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment