Axionlike particles (ALPs) are hypothetical light (sub-eV) bosons predicted in some extensions of the Standard Model of particle physics. In astrophysical environments comprising high-energy gamma rays and turbulent magnetic fields, the existence of ALPs can modify the energy spectrum of the gamma rays for a sufficiently large coupling between ALPs and photons. This modification would take the form of an irregular behavior of the energy spectrum in a limited energy range. Data from the H.E.S.S. observations of the distant BL Lac object PKS 2155-304 (z = 0.116) are used to derive upper limits at the 95% C.L. on the strength of the ALP coupling to photons, $g_{gamma a} < 2.1times 10^{-11}$ GeV$^{-1}$ for an ALP mass between 15 neV and 60 neV. The results depend on assumptions on the magnetic field around the source, which are chosen conservatively. The derived constraints apply to both light pseudoscalar and scalar bosons that couple to the electromagnetic field.