Magento – How to get option_id of an option by label? (magento 2)

attribute-optionsattributesmagento2

I want to get the option_id of one of the options on an attribute, but I only know the label of the option (by label, I mean the 'value' column in eav_attribute_option_value).

How can I get it?

Right now I have the following code:

/**  @var \Magento\Catalog\Model\Product\Attribute\Repository $productAttributeRepository */

$options = $productAttributeRepository->get('treadwidth')->getOptions();

foreach ($options as $option) {
    var_dump($option->getValue());  // option_id
    var_dump($option->getLabel());  // value
}

In other words, it is possible for me to loop through each option and check if the option_id matches the one I want, but I wan't to do this directly. Is it possible?

Best Answer

If you have the attribute, you can do this:

 $id = $attribute->getSource()->getOptionId($label);
Related Topic