Skip to content

Instantly share code, notes, and snippets.

@kuroisuna
Last active November 26, 2015 21:09
Show Gist options
  • Save kuroisuna/c6579eed8eae5a9b5d1e to your computer and use it in GitHub Desktop.
Save kuroisuna/c6579eed8eae5a9b5d1e to your computer and use it in GitHub Desktop.
Devuelve el elemento de un array que tenga la llave más parecida a la que le especifiquemos
<?php
if (!function_exists('get_similar_key')) {
/**
* Devuelve el elemento de un array que tenga la llave más parecida
* al string que le especifiquemos
*
* Uso:
* $array = ['azul' => 264, 'verde': 164, 'amarillo' => 25];
* get_similar_key('azulado', $array); // 264
* get_similar_key('casi verde', $array); // 164
* get_similar_key('casi verde', $array, true); // 'verde'
*
* @param string $text
* @param mixed $elements
* @param bool $return_key = false
* @return string
*/
function get_similar_key($text, $elements, $return_key = false)
{
// Minúsculas para mejorar la búsqueda
$text = mb_strtolower($text);
// Almacenaremos todas las llaves parecidos en un array, junto con el
// índice de similitud devuelto por similar_text()
$index = [];
foreach ($elements as $key => $value) {
$key = mb_strtolower($key);
$index[$key] = similar_text($text, $key);
}
// El elemento que tenga el mayor índice de similitud será
// el que devolveremos, como solo tenemos el valor, lo ubicamos
// por array_search()
$the_one = array_search(max($index), $index);
// Tenemos la opción de devolver la llave del elemento en vez de su valor
if ($return_key) {
return $the_one;
}
// $elements puede ser un array o un objeto, por lo que usamos la notación
// correspondiente para devolver el elemento
return is_array($elements) ? $array[$the_one] : $array->$the_one;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment