I want to convert this array that Array[4] should not give null it can give blank space (empty string).
Array (
[0] => 1
[1] => 4
[2] => 0
[3] => V
[4] =>
[5] => N
);
(The reason for the change, unrelated to the general question)
Fatal error: Uncaught exception
'PDOException' with message 'Database
error [23000]: Column 'message' cannot
be null, driver error code is 1048' in
PHP 5.3+
$array = array_map(function($v){
return (is_null($v)) ? "" : $v;
},$array);
Then you should just loop through array elements, check each value for null and replace it with empty string. Something like that:
foreach ($array as $key => $value) {
if (is_null($value)) {
$array[$key] = "";
}
}
Also, you can implement checking function and use array_map() function.
There is even better/shorter/simpler solution. Compilation of already given answers. For initial data
[1, 4, "0", "V", null, false, true, 'true', "N"]
with
$result = array_map('strval', $arr);
$result will be
['1', '4', '0', 'V', '', '', '1', 'true', 'N']
This should work even in php4 :)
This will map the array to a new array that utilizes the null ternary operator to either include an original value of the array, or an empty string if that value is null.
$array = array_map(function($v){
return $v ?: '';
},$array);
You can use this instead.
array_map(function($val){return is_null($val)? "" : $val;},$result);
Here's a technique I haven't seen mentioned in the above answers:
$val = strval(#$arr["notfound"]); // will not generate errors and
// defaults to an empty string
This is super handy for $_GET parameter loading to keep things short and readable. Bonus, you can replace strval() with trim() ... or with intval() if you only accept integers.
The default for intval will be 0 if missing or a non-numeric value. The default for strval is "" if empty, null or false.
$val_str = strval(#$_GET['q']);
$val_int = intval(#$_GET['offset']);
See DEMO
Now for an array, you'll still need to loop over every value and set it. But it's very readable, IMO:
$arr = Array (1, 4, "0", "V", null, false, true, 'true', "N");
foreach ($arr as $key=>$value) {
$arr[$key] = strval($value);
}
echo ("['".implode("','", $arr)."']");
Here is the result:
['1','4','0','V','','','1','true','N']
Interesting is that true becomes "1", but 'true' stays a string and that false becomes and empty string "".
Now the same data using $arr[$key] = intval($value); produces this result:
['1','4','0','0','0','0','1','0','0']
foreach($array as $key=>$value)
{
if($value===NULL)
{
$array[$key]="";
}
}
Use this function. This will replace null to empty string in nested array also
$arr = array(
"key1"=>"value1",
"key2"=>null,
"key3"=>array(
"subkey1"=>null,
"subkey2"=>"subvalue2"),
"key4"=>null);
echo json_encode(replace_null_with_empty_string($arr));
function replace_null_with_empty_string($array)
{
foreach ($array as $key => $value)
{
if(is_array($value))
$array[$key] = replace_null_with_empty_string($value);
else
{
if (is_null($value))
$array[$key] = "";
}
}
return $array;
}
Output will be :
{
"key1": "value1",
"key2": "",
"key3": {
"subkey1": "",
"subkey2": "subvalue2"
},
"key4": ""
}
Try online here : https://3v4l.org/7uXTL
This can be solved in one line using:
array_walk($array_json_return,function(&$item){$item=strval($item);});
here $array_json_return is the array.
Related
This is my data:
$d = $request->request->get('data');
The output:
[{"name":"form[id]","value":"10"},{"name":"form[name]","value":"Telefon2"},{"name":"form[uuid]","value":"bb80878ad4"},{"name":"form[productgroup]","value":"6"},{"name":"form[category]","value":"1"},{"name":"form[documents]","value":"7"}
I want to create a new array, that is removing extracting the variable inside the brackets.
function trim($d) {
preg_match('#\[(.*?)\]#', $d, $match);
return $match[1];
}
$dData = array_combine(array_column(trim($d), 'name'), array_column($d, 'value'));
$json = json_encode($dData);
But the error is
Warning: preg_match() expects parameter 2 to be string, array given
You're going to need to do a few things before you begin.
Firstly, rename the trim function to something like extract_name because PHP already has a built in trim function that removes whitespace from a string - or any character present in the character mask.
Secondly, you are going to need to iterate over each of the elements in the name column. You will notice the error you are getting from preg_match is because you are passing all values in one go.
Thirdly, I am assuming that the value of $d is an array of PHP objects. This is done, and assumed, in my solution using $d = json_decode($d);.
Using array_map instead of a foreach means we can have a nice one liner:
function extract_name($d) {
preg_match('#\[(.*?)\]#', $d, $match);
return $match[1];
}
$dData = array_combine(array_map('extract_name', array_column($d, 'name')), array_column($d, 'value'));
The output being:
array:6 [
"id" => "10"
"name" => "Telefon2"
"uuid" => "bb80878ad4"
"productgroup" => "6"
"category" => "1"
"documents" => "7"
]
Live demo
I believe you need smth like this
$d = ['{"name":"form[id]","value":"10"}', '{"name":"form[name]","value":"Telefon2"}', '{"name":"form[uuid]","value":"bb80878ad4"}', '{"name":"form[productgroup]","value":"6"}'];
function combine(array $d): array
{
$res = [];
foreach ($d as $item) {
$value = json_decode($item, true);
preg_match('#\[(.*?)\]#', $value['name'], $match);;
$columnName = $match[1];
$res[$columnName] = $value['value'];
}
return $res;
}
$dData = combine($d);
$json = json_encode($dData);
echo $json;```
I have one array and i want to keep only blank values in array in php so how can i achieve that ?
My array is like
$array = array(0=>5,1=>6,2=>7,3=>'',4=>'');
so in result array
$array = array(3=>'',4=>'');
I want like this with existing keys.
You can use array_filter.
function isBlank($arrayValue): bool
{
return '' === $arrayValue;
}
$array = array(0 => 5, 1 => 6, 2 => 7, 3 => '', 4 => '');
var_dump(array_filter($array, 'isBlank'));
use for each loop like this
foreach($array as $x=>$value)
if($value=="")
{
$save=array($x=>$value)
}
if you want print then use print_r in loop
there is likely a fancy built in function but I would:
foreach($arry as $k=>$v){
if($v != ''){
unset($arry[$k]);
}
}
the problem is; you are not using an associative array so I am pretty sure the resulting values would be (from your example) $array = array(0=>'',1=>''); so you would need to:
$newArry = array();
foreach($arry as $k=>$v){
if($v == ''){
$newArry[$k] = $v;
}
}
I have an array as such:
$array = ["1","0","0","1","1"]
//replace with
$newArray = ["honda","toyota","mercedes","bmw","chevy"]
// only if the original array had a value of "1".
// for example this is my final desired output:
$newArray = ["honda","0","0","bmw","chevy"]
I want to change each value in a specific order IF and only if the array value is equal to "1".
For example the values, "honda", "toyota", "mercedes", "bmw", "chevy" should only replace the array values if the value is "1" otherwise do not replace it and they must be in the right position for example the first element in the array must only be changed to honda, not toyota or any of the other values.
I know I must iterate through the array and provide an if statement as such:
foreach($array as $val) {
if($val == 1){
//do something
} else {
return null;
}
}
Please guide me in the right direction and describe how to replace the values in order, so that toyota cannot replace the first array value only the second position.
You can so something like this - iterating over the array by reference and replacing when the value is 1 (string) and the value in the replace array exists:
foreach($array as $key => &$current) {
if($current === '1' && isset($replace[$key]))
$current = $replace[$key];
}
Output:
Array
(
[0] => honda
[1] => 0
[2] => 0
[3] => bmw
[4] => chevy
)
As per your comment, to output an imploded list of the cars that do have values, you can do something like this - filtering out all zero values and imploding with commas:
echo implode(
// delimiter
', ',
// callback - filter out anything that is "0"
array_filter($array, function($a) {
return $a != '0';
})
);
Currently, our if is asking if $val is true (or if it exists) while your numeric array's values are strings.
Try this:
$array = ["1","0","0","1","1"]
$newArray = ["honda","toyota","mercedes","bmw","chevy"]
foreach($array as $key => $val) {
if($val === '1'){ // if you only want honda
$array[$key] = $newArray[$key];
} else {
return null;
}
}
PHP Code
$array = array("1","0","0","1","1");
$newArray = array("honda","toyota","mercedes","bmw","chevy");
foreach($array as $key => $val) {
if($val === '1')
$array[$key] = $newArray[$key];
}
Would produce the answer you're looking for
I'm trying to increment the value for $variable each time a duplicate variable occurs. I'm not sure if this is syntactically correct, but I think this is semantically correct. var_dump seems to spit out the correct outputs, but i get this error: Notice: Undefined index...
$newarray = array();
foreach ($array as $variable)
{
$newarray[$variable]++;
var_dump($newarray);
}
$array = (0 => h, 1 => e, 2 => l, 3=> l, 4=> o);
goal:
'h' => int 1
'e' => int 1
'l' => int 2
'o' => int 1
My code works, it's just that I get some weird NOTICE.
$newarray = array();
foreach ($array as $variable)
{
if (!isset($newarray[$variable])) {
$newarray[$variable] = 0;
}
$newarray[$variable]++;
}
Take a look at the function array_count_values(). It does exactly what you are trying to do.
Sample from php.net:
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
Result:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
In modern PHP, you can avoid the isset() call by leveraging the null coalescing operator. In the snippet below, the technique sets the variable to 0 if the variable is not yet declared. Then you can freely use a range of shorthand manipulations such as concatenation, arithmetic, etc.
$new = [];
foreach ($array as $v) {
$new[$v] = ($new[$v] ?? 0) + 1;
}
Or if you want to continue using ++, then you can use the "null coalescing assignment operator". The logic on the right side of assignment is not even executed if the variable is already declared. The below snippet will perform identically to the above snippet.
$new = [];
foreach ($array as $v) {
$new[$v] ??= 0;
++$new[$v];
}
<?php
$newarray = array();
foreach ($array as $variable) {
if ( !array_key_exists($variable, $newarray) ) {
$newarray[$variable] = 0;
}
++$newarray[$variable];
}
var_dump($newarray);
But you could also use array_count_values() instead.
$newarray = array();
foreach ($array as $variable)
{
if(!isset($newarray[$variable]))
$newarray[$variable] = 0;
$newarray[$variable]++;
var_dump($newarray);
}
You are incrementing the wrong thing, try this instead:
foreach ($array as $key => $variable) {
$array[$key]++;
var_dump($array);
}
I am not finding what might be the problem in my program.
I am having an array like this
$arr = array("1", "urgent", "4", "low", "15", "avg");
When i am searching this array using
$key = array_search("4", $arr);// Working
Its is giving me the index of that element;
But when i am searching for "1" it is not giving me any index.
$key = array_search("4", $arr); // Not working here - for searching "1"
What might be the problem.
Thank You
http://ideone.com/e1n3r Your code does work fine. It returns key == 0, which is the key, where "1" is stored.
To get the difference between 0 and false you should use === operator, or its contrary !==:
$arr = array("1", "urgent", "4", "low", "15", "avg");
$key1 = array_search("1", $arr);
var_dump($key1 === false); // false (value exists)
var_dump($key1 !== false); // true (value exists)
$key21 = array_search("21", $arr);
var_dump($key21 === false); // true (value does not exist)
var_dump($key21 !== false); // false (value does not exist)
array_search return key value of array.
$arr = array("1", "urgent", "4", "low", "15", "avg");
$key = array_search("4", $arr);
// give output is 2 which is key value
$key = array_search("1", $arr);
//give output is 0 which is key value
I think you are using $key in thewrong way. $key = 0 and now if you do boolean evaluation it will act as false. You should use something like if($key >= 0) or if(is_int($key))
Remember that 0 is evaluated to FALSE in php.
so..
if($index = array_search("1",$arr)) {
//will actually evaluate to false
}
In case you are using it this way and think it's not working because the conditional isn't technically failing, the value is evaluated as FALSE.