-1

Array ( [status] => 1 [message] => Logged In Successfully. )

I Want to access status from this array like string. I fetch this Response from API. It's look not good.not like array or not like json. I am not able to access key,so any one can help me, now.

enter image description here

  • Please look my issue. => https://www.awesomescreenshot.com/image/17982284?key=2822411b46599d7f051614b7ef2117eb – Parmar Satish Dec 06 '21 at 05:09
  • 1
    _"I fetch this Response from API"_... then the API is broken. It most definitely should not be responding with PHP `print_r()` output – Phil Dec 06 '21 at 06:09

2 Answers2

1

You could achieve this using preg_match perhaps? See it working over at 3v4l.org but it is not a very dynamic solution and I'm assuming the status will always be a single integer.

preg_match('/(\Sstatus\S => \d)/',
    'Array ( [status] => 1 [message] => Logged In Successfully. )',
    $matches
);

if(!empty($matches))
{
    $status = (int) $matches[0][strlen($matches[0]) -1]; // 1
}
Jaquarh
  • 6,493
  • 7
  • 34
  • 86
0

To improve @Jaquarh's answer, you could write this function that helps you extract the values using any desired string, key and expected type.

I have added a few features to the function like not minding how many spaces come between the => separator in the string, any value-type matching, so that it can retrieve both numeric and string values after the => separator and trimming of the final string value. Finally, you have the option of casting the final value to an integer if you want - just supply an argument to the $expected_val_type argument when you call the function.

$my_str is your API response string, and $key_str is the key whose value you want to extract from the string.

function key_extractor($my_str, $key_str, $expected_val_type=null) {
    
    // Find match of supplied $key_str regardless of number of spaces
    // between key and value.
    preg_match("/(\[" . $key_str . "\]\s*=>\s*[\w\s]+)/", $my_str, $matches); 
   
    if (!empty($matches)) {
        // Retrieve the value that comes after `=>` in the matched
        // string and trim it.
        $value = trim(substr($matches[0], strpos($matches[0], "=>") + 2));
     
        // Cast to the desired type if supplied.
        if ($expected_val_type === 'int') {
            return ((int) $value);
        } 

        return $value;
    }
  
    // Nothing was found so return null.
    return NULL;
}

You could then use it like this:

key_extractor($res, 'status', 'int');

$res is your API response string.

Chizaram Igolo
  • 907
  • 8
  • 18