2

What's the best method to return the corresponding array name (stone, kilogram, pound) from knowing just the acronym value (st, kg, lb)?

        "weight" => [

            "stone" => [
                "acronym" => "st"
            ],
            "kilogram" => [
                "acronym" => "kg"
            ],
            "pound" => [
                "acronym" => "lb"
            ]

        ];
2
  • 1
    Iterate array searching for your acronym. Commented Jan 31, 2014 at 6:14
  • I've tried array_search('kg', array_keys($weightArray)); but array_keys() returns the first tier of keys. 0 => stone, 1 => kilogram etc. I'm trying to get 'kilogram' from kg. Commented Jan 31, 2014 at 6:18

5 Answers 5

1
function name($array,$t){
    foreach($array as $k=>$a){
       if($a['acronym']===$t){return $k;}
    }

}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use strtr(); (if its ok to change your array)

$converter = array(
   'st' => 'stone',
   'kg' => 'kilogram',
   'lb' => 'pound',
);

echo strtr('st', $converter); // stone

Comments

0

A bit lengthy:

foreach($mainArray['weight'] as $key=>$value) {
  if(is_array($value)) {
    if(in_array($acronymValue, $value)) {
     echo $key. "has the acronym value";
     break;
  }
  }
}

Here is its working demo : Fiddle

1 Comment

That would give you a false positive for kilograms, if $mainArray['weight']['stone']['something'] = 'kg'
0

While question is already answered, Still I think to add a loop-less version using callback anonymous function.

function getData($arr, $needle)
{
    $f = array_filter($arr['weight'], function($v) use ($needle) {
        if($v["acronym"] == $needle){
            return $v;
        }
    } );
    list($k, $v) = each($f);

    return $k;

}

echo getData($arr, "kg"); 

Comments

0

From PHP8.4, the best performing native function to short-circuit upon finding the first qualifying item and return its parent level key is array_find_key(). Demo

$array = [
    "weight" => [
        "stone" => ["acronym" => "st"],
        "kilogram" => ["acronym" => "kg"],
        "pound" => ["acronym" => "lb"]
    ]
];

var_export(
    array_find_key($array['weight'], fn($row) => $row['acronym'] === 'kg')
);
// output: 'kilogram'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.