How to get Key from this string array in PHP [duplicate] - php

This question already has answers here:
How create an array from the output of an array printed with print_r?
(11 answers)
Closed 1 year ago.
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.

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
}

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.

Related

PHP Regex for Paypal Payflow response

I am working on Paypal Payflow for payment and right now I am having trouble extracting the Paypal response.
Paypal responses are sent in a format as given below
RESULT=0&RESPMSG=Approved&SECURETOKEN[25]=Fj+1AFUWft0+I0CUFOKh5WA== &SECURETOKENID=9a9ea8208de1413abc3d60c86cb1f4c5
The value inside the square braces [] is the length of the actual value. For example, SECURETOKEN is a parameter and it's value is 'Fj+1AFUWft0+I0CUFOKh5WA=='. is 25 characters long.
How can I extract each parameter and it's corresponding value from the result in PHP. I am not so good with regex and I was unable to find any solution online.
Splitting with & and = does not work in this case.
The string looks an url, so the simple approch is use [parse_str()][1] it will transform the given string into an array 'well formated'.
Important the return of function will be store in the second argument ($keys in this example).
Ideone - example
$str = 'RESULT=0&RESPMSG=Approved&SECURETOKEN[25]=Fj+1AFUWft0+I0CUFOKh5WA== &SECURETOKENID=9a9ea8208de1413abc3d60c86cb1f4c5';
parse_str($str, $keys);
print_r($keys);
Output:
Array
(
[RESULT] => 0
[RESPMSG] => Approved
[SECURETOKEN] => Array
(
[25] => Fj 1AFUWft0 I0CUFOKh5WA==
)
[SECURETOKENID] => 9a9ea8208de1413abc3d60c86cb1f4c5
)
Using this answer to parse the response into an array is the correct start. This is how to access those values from the array:
$str = 'RESULT=0&RESPMSG=Approved&SECURETOKEN[25]=Fj+1AFUWft0+I0CUFOKh5WA== &SECURETOKENID=9a9ea8208de1413abc3d60c86cb1f4c5';
parse_str( $str, $values );
Now, to get the values you want:
$tokens = $values['SECURETOKEN'];
// results in an array: ['25' => 'Fj+1AFUWft0+I0CUFOKh5WA=='];
$token = reset( $tokens ); // results in 'Fj+1AFUWft0+I0CUFOKh5WA=='
$length = key( $tokens ); // results in '25'

array_filter with element modification [duplicate]

This question already has answers here:
Explode string on commas and trim potential spaces from each value
(11 answers)
Closed 6 months ago.
I'm trying to make a clean array from a string that my users will define.
The string can contain non-valid IDs, spaces, etc. I'm checking the elements using a value object in a callback function for array_filter.
$definedIds = "123,1234,1243, 12434 , asdf"; //from users panel
$validIds = array_map(
'trim',
array_filter(
explode(",", $definedIds),
function ($i) {
try {
new Id(trim($i));
return true;
} catch (\Exception $e) {
return false;
}
}
)
);
This works fine, but I'm applying trim twice. Is there a better way to do this or a different PHP function in which I can modify the element before keeping it in the returned array?
NOTE: I also could call array_map in the first parameter of array_filter, but I would be looping through the array twice anyway.
It depends on whether you care about performance. If you do, don't use map+filter, but use a plain for loop and manipulate your array in place:
$arr = explode(',', $input);
for($i=count($arr)-1; $i>=0; $i--) {
// make this return trimmed string, or false,
// and have it trim the input instead of doing
// that upfront before passing it into the function.
$v = $arr[$i] = Id.makeValid($arr[$i]);
// weed out invalid ids
if ($v === false) {
array_splice($arr, $i, 1);
}
}
// at this point, $arr only contains valid, cleaned ids
Of course, if this is inconsequential code, then trimming twice is really not going to make a performance difference, but you can still clean things up:
$arr = explode(',', $input);
$arr = array_filter(
array_map('Id.isValidId', $arr),
function ($i) {
return $i !== false;
}
);
In this example we first map using that function, so we get an array of ids and false values, and then we filter that so that everything that's false gets thrown away, rather than first filtering, and then mapping.
(In both cases the code that's responsible for checking validity is in the Id class, and it either returns a cleaned id, or false)
Actually you can do it by different way but If I were you then I'll do it this way. Here I just used only one trim
<?php
$definedIds = "123,1234,1243, 12434 , asdf"; //from users panel
function my_filter($b){
if(is_numeric($b)){
return true;
}
}
print '<pre>';
$trimmed = array_map('trim',explode(',',$definedIds));
print_r(array_filter($trimmed,my_filter));
print '</pre>';
?>
Program Output:
Array
(
[0] => 123
[1] => 1234
[2] => 1243
[3] => 12434
)
DEMO: https://eval.in/997812

Regular expression to get the value from array

I need to get the value for a certain key, they key is not the same all the time.
initial part remains same but every time I get new id added in the end.
My array is like this:
senario 1:
Array
(
[custom_194_1] => 123
[_f_upload] => Save
)
senario 2:
Array
(
[custom_194_2] => 456
[_f_upload] => Save
)
I need to get the value 123 in senario 1, 456 in senario 2.
Can anyone please help me on how to get the value from this array key.
If your key is always the first element, and the array is $array the fastest way is:
$result = reset($array);
Or if you don't want to mess with the array's internal pointer:
$result = array_values($array)[0];
If you want the value of the key:
$key = array_keys($array)[0];
Thanks for your time guys. I'm using foreach to loop through and then checking with every key with substring. Hope it helps someone in future, not the very best solution though.
foreach($fields as $key => $val)
{
if(substr($key,0,10)=='custom_194'){
$realValue = $val;
echo "<br>value i'm looking for:";print_r($val);
}
}
Because you stated that you want the number at the end of the key and because you appear to want to learn more about regular expressions... This is not a hard task to do with preg_match.
Assume $array is the array that you begin with that has all the key=>val values.
foreach($fields as $key=>$val)
{
if(preg_match('/^custom_194_([0-9]+)$/', $key, $matches))
{
$num = $matches[1];
print "Key number $num has value $val\n";
}
}
The regular expression is ^custom_194_([0-9]+)$. The ^ means "beginning of the string." The $ means "end of the string." You can see that we explicitly spell out custom_194_. Then, we use ( and ) to identify a substring that we want to keep in the matches array. Inside ( and ), we look for the characters 0 through 9 using [0-9]. The + means "1 or more characters." So, we want 1 or more 0 through 9 characters.
The match array contains the entire string matched in the first index and then each sub-match in the remaining indexes. We only have one sub-match, which will be in index 1. So, $num is in $matches[1].

put blank value instead of null in array value php [duplicate]

This question already has answers here:
How to cast array elements to strings in PHP?
(7 answers)
Closed 10 months ago.
There is dynamic array that we received from database .
It has some null value.
So I want to put empty string instead of null in value
I know, I can check with isset function. But it is dynamic array so it is difficult to find out number of key value pairs.
$hoteldetails = get_hotel_detail($hotel_id);
$response=json_encode($HotelDetail);
get Hotel details fetching from database. It may have some null value
Ex- Latitude or longitude can have null. When I encode json_encode it display null.
I also tried array_filter but it is removing null value element. I do not want to remove key value element.
PHP Code (modified from Replacing empty string with nulls in array php):
$array = array(
'first' => NULL,
'second' => NULL
);
echo json_encode($array);
$array2 = array_map(function($value) {
return $value === NULL ? "" : $value;
}, $array); // array_map should walk through $array
echo json_encode($array2);
Output:
{"first":null,"second":null}
{"first":"","second":""}

php challenge: parse pseudo-regex

I have a challenge that I have not been able to figure out, but it seems like it could be fun and relatively easy for someone who thinks in algorithms...
If my search term has a "?" character in it, it means that it should not care if the preceding character is there (as in regex). But I want my program to print out all the possible results.
A few examples: "tab?le" should print out "table" and "tale". The number of results is always 2 to the power of the number of question marks. As another example: "carn?ati?on" should print out:
caraton
caration
carnaton
carnation
I'm looking for a function that will take in the word with the question marks and output an array with all the results...
Following your example of "carn?ati?on":
You can split the word/string into an array on "?" then the last character of each string in the array will be the optional character:
[0] => carn
[1] => ati
[2] => on
You can then create the two separate possibilities (ie. with and without that last character) for each element in the first array and map these permutations to another array. Note the last element should be ignored for the above transformation since it doesn't apply. I would make it of the form:
[0] => [carn, car]
[1] => [ati, at]
[2] => [on]
Then I would iterate over each element in the sub arrays to compute all the different combinations.
If you get stuck in applying this process just post a comment.
I think a loop like this should work:
$to_process = array("carn?ati?on");
$results = array();
while($item = array_shift($to_process)) {
$pos = strpos($item,"?");
if( $pos === false) {
$results[] = $item;
}
elseif( $pos === 0) {
throw new Exception("A term (".$item.") cannot begin with ?");
}
else {
$to_process[] = substr($item,0,$pos).substr($item,$pos+1);
$to_process[] = substr($item,0,$pos-1).substr($item,$pos+1);
}
}
var_dump($results);

Categories