{"10": "OK"} How to get the number 10 from this line?

  • a) Is it a string? b) 10 is always in the first position and in quotes? - DNS
  • one
  • You can also read about the row scanner - DNS
  • json_decode gives nothing, I need the number 10 - zoinx2012
  • What json_decode did not please? - dakemu

3 answers 3

<?php $array = json_decode('{"10":"OK"}', 1); echo key($array); 

    The simplest code, works for any line, pulls out all the numbers.

     <?php $str = '{"10":"OK"}'; $strWithoutChars = preg_replace('/[^0-9]/', '', $str); echo $strWithoutChars; ?> 
    • Any flag g not necessary? - Qwertiy
    • one
      Why is the flag here if it works without a flag? You can always check here phptester.net - labris
    • one
      In this case it is more correct to say “leaves”, but not “pulls out”. Pulls out preg_match_all('~\d+~', $s, $matches) . - Wiktor Stribiżew

    How to get a number out of line?

     $str = "1 ромашка, 2 ромашка, 3 ромашка, 5!"; preg_match_all("/\d+/", $str, $matches); print_r($matches); // [1, 2, 3, 5] 

    {"10": "OK"}

    This is json. And you need to parse it, like json.

    Php has a json_decode function for this:

    json_decode (string $ json [, bool $ assoc = false [, int $ depth = 512 [, int $ options = 0]]]);

    Note the second parameter: bool assoc = false

    If you pass true as the second parameter, the result of the parsing is not an object, but an array.

     $arr = json_decode('{"10":"OK"}', true); // ['10' => 'OK'] $keys = array_keys($arr); // ['10'] echo $keys[0]; // 10