-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

2
  • Please look my issue. => awesomescreenshot.com/image/… Commented Dec 6, 2021 at 5: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 Commented Dec 6, 2021 at 6:09

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.