I'm sorry but i researched a lot about this issue.
Is there a standard function to search and replace array elements?
str_replace doesn't work in this case, because what i wanna search for is an empty string '' and i wanna replace them with NULL values
this is my array:
$array = (
'first' => '',
'second' => '',
);
and i want it to become:
$array = (
'first' => NULL,
'second' => NULL,
);
Of course i can create a function to do that, I wanna know if there is one standard function to do that, or at least a "single-line solution".
I don't think there's such a function, so let's create a new one
$array = array(
'first' => '',
'second' => ''
);
$array2 = array_map(function($value) {
return $value === "" ? NULL : $value;
}, $array); // array_map should walk through $array
// or recursive
function map($value) {
if (is_array($value)) {
return array_map("map", $value);
}
return $value === "" ? NULL : $value;
};
$array3 = array_map("map", $array);
As far as I know, there is no standard function for that, but you could do something like:
foreach ($array as $i => $value) {
if ($value === "") $array[$i] = null;
}
Now you can use arrow function also:
$array = array_map(fn($v) => $v === '' ? null : $v, $array);
You can use array_walk_recursive function.
$array = [
'first' => '',
'second' => ''
];
array_walk_recursive($array, function(&$value) { $value = $value === "" ? NULL : $value; });
Related
I have a string as:
$string = "My name is {name}. I live in {detail.country} and age is {detail.age}";
and I have an array like that and it will be always in that format.
$array = array(
'name' => 'Jon',
'detail' => array(
'country' => 'India',
'age' => '25'
)
);
and the expected output should be like :
My name is Jon. I live in India and age is 25
So far I tried with the following method:
$string = str_replace(array('{name}','{detail.country}','{detail.age}'), array($array['name'],$array['detail']['country'],$array['detail']['age']));
But the thing is we can not use the plain text of string variable. It should be dynamic on the basis of the array keys.
You can use preg_replace_callback() for a dynamic replacement:
$string = preg_replace_callback('/{([\w.]+)}/', function($matches) use ($array) {
$keys = explode('.', $matches[1]);
$replacement = '';
if (sizeof($keys) === 1) {
$replacement = $array[$keys[0]];
} else {
$replacement = $array;
foreach ($keys as $key) {
$replacement = $replacement[$key];
}
}
return $replacement;
}, $string);
It also exists preg_replace() but the above one allows matches processing.
You can use a foreach to achieve that :
foreach($array as $key=>$value)
{
if(is_array($value))
{
foreach($value as $key2=>$value2)
{
$string = str_replace("{".$key.".".$key2."}",$value2,$string);
}
}else{
$string = str_replace("{".$key."}",$value,$string);
}
}
print_r($string);
The above will only work with a depth of 2 in your array, you'll have to use recurcivity if you want something more dynamic than that.
Here's a recursive array handler: http://phpfiddle.org/main/code/e7ze-p2ap
<?php
function replaceArray($oldArray, $newArray = [], $theKey = null) {
foreach($oldArray as $key => $value) {
if(is_array($value)) {
$newArray = array_merge($newArray, replaceArray($value, $newArray, $key));
} else {
if(!is_null($theKey)) $key = $theKey . "." . $key;
$newArray["{" . $key . "}"] = $value;
}
}
return $newArray;
}
$array = [
'name' => 'Jon',
'detail' => [
'country' => 'India',
'age' => '25'
]
];
$string = "My name is {name}. I live in {detail.country} and age is {detail.age}";
$array = replaceArray($array);
echo str_replace(array_keys($array), array_values($array), $string);
?>
echo "my name is ".$array['name']." .I live in ".$array['detail']['countery']." and my age is ".$array['detail']['age'];
I have the following array:
array(5) {
["destino"]=> string(11) "op_list_gen"
["id_terminal"]=> string(0) ""
["marca"]=> string(2) "--"
["tipo"]=> string(2) "--"
["lyr_content"]=> string(14) "aawaw"
}
How can I remove the values "--" and empty values from the array?
I have tried using a foreach and removing the elements found with unset but it´s not working.
foreach ($array as $key => $arra) {
if(array_key_exists('--', $array)){
unset($arra[$key]);
}
}
You can use array_filter to solve this:
$arr = [
"destino" => "op_list_gen",
"id_terminal" => "",
"marca" => "--",
"tipo" => "--",
"lyr_content" => "aawaw"
];
$newArr = array_filter($arr, function($value) {
return !in_array($value, ['', '--']);
});
demo: https://ideone.com/oot7lZ
$array = [
"destino" => "op_list_gen",
"id_terminal" => "",
"marca" => "--",
"tipo" => "--",
"lyr_content" => "aawaw"
];
$new_array = array_filter($array, function($item){
if($item != '--' || $item != '')
return $item;
})
var_dump($new_array)
array_filter() will take each entry and return it if it's not -- or ''
Generic approach should look like that:
$filter = function(...$excluded) {
return function ($value) use ($excluded) {
return !in_array($value, $excluded);
};
};
$newArray = array_filter($array, $filter('', '--'));
This approach is reusable, because you don't need to hardcode values right insight your filtering function.
You could remove values by simply looping over the array, creating a new array in the process:
$myarray = array(
"destino" => "op_list_gen",
"id_terminal" => "",
"marca" => "--",
"tipo" => "--",
"lyr_content" => "aawaw",
}
$newarray = array();
foreach($myarray as $key => $value) {
if($value != "--" && $value != "") {
$newarray[$key] = $value;
}
}
Or, more elegantly, you could use the array_filter function. It takes a callback function that, for each value, decides whether to include it. This also returns a new array:
$newarray = array_filter($myarray, function($elem) {
if($elem != "" && $elem != "--") return $elem;
});
As all the other answers say, array_filter is a good way to go about that. However, this is returning a new array and doesn't actually modify the original array. If that's what you're looking for, this might be a different approach:
// Start infinite loop
while(true){
// Check for value in array
if (($key = array_search('--', $arr)) !== false || ($key = array_search('', $arr)) !== false) {
// Unset the key
unset($arr[$key]);
// Reset array keys
$arr = array_values($arr);
} else {
// No more matches found, break the loop
break;
}
}
Use array_filter:
$original = [
'destino' => 'op_list_get',
'id_terminal' => '',
'marca' => '--',
'tipo' => '--',
'lyr_content' => 'aawaw',
];
// values you want to filter away
$disallowArray = ['', '--'];
$filteredResult = array_filter($original, function($val) use($disallowArray) {
// check that the value is not in our disallowArray
return \in_array($val, $disallowArray, true) === false;
});
Result:
Array
(
[destino] => op_list_get
[lyr_content] => aawaw
)
Say I have an array that looks like this:
Array
(
[0] =>
[1] => 2017-01-01 00:00:00
)
How can I dynamically check to see if the area has any empty values?
You can use empty():
$array = [
null,
'2017-01-01 00:00:00',
'',
[],
# etc..
];
foreach($array as $key => $value){
if(empty($value)){
echo "$key is empty";
}
}
See the type comparison table for more information.
You can see if it has any empty values by comparing the array values to the result of array_filter (which removes empty values.)
$has_empty_values = $array != array_filter($array);
Something like
// $array = [ ... ];
$count = count($array);
for( $i=0; $i<=$count; $i++){
if( $array[$count] == 0 ){
// Do something
}
}
For this you have more possibility:
You can use array_filter function without without a second parameter
array_filter([ 'empty' => null, 'test' => 'test']);
but for this be carful because this remove all values which are equal false (null, false, 0)
You can use array_filter function with callback function:
function filterEmptyValue( $value ) {
return ! empty( $value );
}
array_filter([ 'empty' => null, 'test' => 'test'], 'filterEmptyValue');
You can use foreach or for:
$array = ['empty' => null, 'test' => 'test'];
foreach($array as $key => $value) {
if(empty($value)) {
unset($array[$key]);
}
}
$array = [null, 'test'];
for($i = 0; $i < count($array); $i++){
if(empty($array[$i])) {
unset($array[$i]);
}
}
This is samples so you must think and make good solution for your problem
I have an array like this
$a = array(
'b' => array(
'two' => false,
'three' => '',
'four' => null,
'five' => array(
'fp' => null,
'kp' => null
),
'six' => array()
),
'c' => ' ',
'd' => null
);
I want to remove only null and empty keys from this n-level array. And finally I should get this:
$a = array(
'b' => array(
'two' => false
),
'c' => ' '
);
I have this function
public function ArrayCleaner($input) {
foreach ($input as &$value) {
if (is_array($value)) {
$value = ArrayCleaner($value);
}
}
return array_filter($input);
}
But, as array_filter states, it will also remove false value key (that I want to preserve). So what change I should make in my function to achieve the expected result?
You are close, just change your code like below by providing the callback function for filtering:
function ArrayCleaner($input) {
foreach ($input as &$value) {
if (is_array($value)) {
$value = ArrayCleaner($value);
}
}
return array_filter($input, function($item){
return $item !== null && $item !== '';
});
}
function ArrayCleaner($input) {
foreach ($input as $key=>&$value) {
if(is_int($key)){
unset($input[$key]);
continue;
}
if (is_array($value)) {
$value = ArrayCleaner($value);
}
}
return array_filter($input, function($item){
return $item !== null && $item !== '';
});
}
But Question: what does empty key mean? 'one' indicates its index is number 0. So if we filter it by using something like is_int($key) , how to deal with '2'=>'this data?' ? it will convert to int(2) in php Array.
I need to search and replace inside an associative array.
ex:
$user = "user1"; // I've updated this
$myarray = array("user1" => "search1", "user2" => "search2", "user3" => "search1" ) ;
I want to replace search1 for search4. How can I achieve this?
UPDATE: I forgot to mention that the array has several search1 values and I just want to change the value where the key is == $user. Sorry for not mention this earlier.
$myarray = array("user1" => "search1", "user2" => "search2" );
foreach($myarray as $key => $val)
{
if ($val == 'search1') $myarray[$key] = 'search4';
}
There's a function for this : array_map().
// Using a lamba function, PHP 5.3 required
$newarray = array_map(
function($v) { if ($v == 'search1') $v = 'search4'; return $v; },
$myarray
);
If you don't want to use a lambda function, define a normal function or method and callback to it.
Why not just do
if (isset($myarray[$user])) $myarray[$user] = 'search4';
$user = "user1";
$myarray = array("user1" => "search1", "user2" => "search2", "user3" => "search1" );
foreach($myarray as $key => $val)
{
if ($val == 'search1' and $key == $user )
{
$myarray[$key] = 'search4';
break;
}
}
print_r($myarray);
Prints:
Array
(
[user1] => search4
[user2] => search2
[user3] => search1
)
$originalArray = array( "user1" => "search1" , "user2" => "search2" );
$pattern = 'search1';
$replace = 'search4';
$replacedArray = preg_replace( '/'.$pattern.'/' , $replace , $originalArray );
Fixes the risk mentioned in comment in response to this solution
Updated
Since the post was updated, and I have had chance to get some sleep, I realized my answer was stupid. If you have a given key and you need to change it's value, why iterate over the whole array?
$user = 'user1';
$search = 'search1';
$replace = 'search4';
$array = array('user1' => 'search1', 'user2' => 'search2');
if (isset($array[$user]) && $search === $array[$user]) $array[$user] = $replace;
Similar to #Joseph's method (pretty much the same), but with a few tweaks:
$user = 'user1';
$array = array("user1" => "search1", "user2" => "search2" );
foreach($array as $key => &$value) {
if ($key === $user) {
$value = 'search4';
break; // Stop iterating after key has been found
}
}
Passing by reference is a nicer way to edit inside foreach, and is arguably quicker.
Search and replace inside an associative array or numeric
Replace value in any associative array and array can be any deep
function array_value_replace($maybe_array, $replace_from, $replace_to) {
if (!empty($maybe_array)) {
if (is_array($maybe_array)) {
foreach ($maybe_array as $key => $value) {
$maybe_array[$key] = array_value_replace($value, $replace_from, $replace_to);
}
} else {
if(is_string($maybe_array)){
$maybe_array = str_replace($replace_from, $replace_to, $maybe_array);
}
}
}
return $maybe_array;
}
if you want for particular key then you just add condition for key in previous ans like.
$user = "user1";
$myarray = array("user1" => "search1", "user2" => "search2" );
foreach($myarray as $key => $val)
{
if ($val == 'search1' && $key == $user) $myarray[$key] = 'search4';
}
Using str_replace should work:
$myarray = array("user1" => "search1", "user2" => "search2" ) ;
$newArray = str_replace('search1', 'search4', $myarray);
Following on from Joseph's answer, using preg_replace may enable you to use the code in other situations:
function pregReplaceInArray($pattern,$replacement,$array) {
foreach ($array as $key => $value) {
$array[$key] = preg_replace($pattern,$replacement,$value);
}
return $array;
}