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

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":""}

Related

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

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.

Array is not getting sorted with sort() function PHP [duplicate]

This question already has answers here:
Sort array not working
(2 answers)
Closed 10 months ago.
I'm trying to sort an array numerically. Here's my code
<?php
$data = '9#Saul,7#Jesse,1#Skyler,6#Walter';
$exp = explode(",",$data);
$expsort = sort($exp);
print_r($expsort);
?>
But it is not working. The output is showing only "1".
You are assigning the value of the sort function -which sorts the argument array itself, and it always returns true and thus you got 1 as a result.
So if you print your original exploded array, it will be sorted. Please note, sort overrides your original array
$data = '9#Saul,7#Jesse,1#Skyler,6#Walter';
$exp = explode(",",$data);
sort($exp);
print_r($exp);

Array_Search For Multiple Same Elements [duplicate]

This question already has answers here:
How to search Array for multiple values in PHP?
(6 answers)
Closed 2 years ago.
there is an array like $arr = array(1,2,3,3,3,4,5) . What if we want to get all indexes that have values 3?
i used array_search(3, $arr) but it just give back an integer and just the first index that has value '3'
how can we get an array like $indexes = array(2,3,4) that shows all indexes that have value 3?
your help will be highly appreciated
You can use array_keys with search value PHP Doc
Demo
array_keys($arr,3)
array_keys() returns the keys, numeric and string, from the array.
If a search_value is specified, then only the keys for that value are
returned. Otherwise, all the keys from the array are returned.
you can use array_keys:
foreach (array_keys($arr) as $key) if ($arr[$key] == 3) $result[] = $key;
With that solution you can create complex filters. In this case we compare every value to be the number three (=== operator). The filter returns the index, when the comparision true, else it will be dropped.
$a = [1,2,3,4,3,3,5,6];
$threes = array_filter($a, function($v, $k) {
return $v === 3 ? $k : false; },
ARRAY_FILTER_USE_BOTH
);
$threes Is an array containing all keys having the value 3.
array(3) { 2, 4, 5 }

Get value of previous array key [duplicate]

This question already has answers here:
PHP get previous array element knowing current array key
(10 answers)
Closed 4 years ago.
So I tried doing this :
$array = array('first'=>'111', 'second'=>'222', 'third'=>'333');
var_dump(prev($array["second"]));
Hoping to get 111 but I get NULL. Why?
$array["second"] returns 222. Shouldn't we get 111 when we use PHP's prev() function?
How to get the previous value of an array if it exists using the key?
Your current value from $array["second"] is not an array and prev takes an array as a parameter.
You have to move the internal pointer of the $array and then get the previous value.
$array = array('first'=>'111', 'second'=>'222', 'third'=>'333');
while (key($array) !== "second") next($array);
var_dump(prev($array));
prev function expects an array as an argument but you're passing a string.
$array["second"] evaluates to '222'
In this case, you point directly the previous value, without iterating the array.
$array = array('first'=>'111', 'second'=>'222', 'third'=>'333');
$keys = array_flip(array_keys($array));
$values = array_values($array);
var_dump($values[$keys['second']-1]);

Easy way to parse array values [duplicate]

This question already has answers here:
Applying a function for each value of an array
(5 answers)
Closed 6 years ago.
Is there util that parses array content without the need of iterating it and parsing each value?
input: ['2','3','7']
output: [2, 3, 7]
This obviously iterates internally, but you don't have to code an iterator:
$output = array_map('intval', $input);
Maps every value in $input to the intval() function and returns the result. For things that cannot be converted into an integer you'll get 0 or for objects, a notice and that value will not be returned.
I can't tell if you want to remove 0 values or not from your comment, but if so:
$output = array_filter(array_map('intval', $input));
You can use array_map
array = ["2","3","4"];
$intArray = array_map('intval', $array);

Categories