How to delete value from mupltiple array using key in PHP - php

I need one help. I need to remove value from multiple array by matching the key using PHP. I am explaining my code below.
$str="ram,,madhu,kangali";
$strid="1,2,,3";
$arr=explode(",",$str);
$arrId=explode(",", $strid);
I have two array i.e-$arr,$arrId which has some blank value. Here I need if any of array value is blank that value will delete and the same index value from the other array is also delete.e.g-suppose for $arr the 1 index value is blank and it should delete and also the the first index value i.e-2 will also delete from second array and vice-versa.please help me.

try this:
$str="ram,,madhu,kangali";
$strid="1,2,,3";
$arr=explode(",",$str);
$arrId=explode(",", $strid);
$arr_new=array();
$arrId_new=array();
foreach ($arr as $key => $value) {
if(($value != "" && $arrId[$key] != "")){
array_push($arr_new, $value);
array_push($arrId_new, $arrId[$key]);
}
}
var_dump($arr_new);
var_dump($arrId_new);

Try:
foreach ($arr as $key => $value) {
if ( empty($value) || empty($arrId[$key]) ) {
unset($arr[$key]);
unset($arrId[$key]);
}
}

You can zip both lists together and then only keep entries where both strings are not empty:
$zipped = array_map(null, $arr, $arrId);
$filtered = array_filter($zipped, function ($tuple) {
return !empty($tuple[0]) && !empty($tuple[1]);
});
$arr = array_map(function($tuple) {return $tuple[0];}, $filtered);
$arrId = array_map(function($tuple) {return $tuple[1];}, $filtered);
Link to Fiddle

Related

PHP How to check if array has not key and value

I am using one custom CMS developed by someone and getting issue to check the array result.
The function returns an array of username by passing userids array.
Example Code
$all_users = "1,5,9,10,25,40"; // getting from database
$user_ids = explode(',', $all_users);
$usernames = get_userids_to_usernames($user_ids); //this returns usernames array by passing uesrids array
If the database has not users in the column than the function is returning weird empty / null array as below.
var_dump($usernames);
array(1) { [""]=> NULL }
print_r($usernames);
(
[] =>
)
Now issue is, I want to check if array is empty or has value in return but I have tried everything is_null, empty, count($usernames) > 0 but none of these working.
Can anyone please help me to check conditionally if array has value or empty like above empty result.
Here is a workaround
if (array_key_exists('', $a) && $a[''] === null) {
unset($a['']);
}
then check on emptiness
You can use in_array to check if the array has an empty value and array_key_exists to check the key.
in_array("", $array)
array_key_exists("", $array)
http://php.net/manual/en/function.in-array.php
http://php.net/manual/fr/function.array-key-exists.php
Iterate through array, and check if keys or values are empty or null
$newarray = [];
foreach($array as $key=>$value)
{
if(is_null($value) || trim($value) == '' || is_null($value) || trim($key) == ''){
continue; //skip the item
}
$newarray[$key] = $value;
}
If you want to use empty with it, try array filter
if (empty(array_filter($arr))) {
//Do something
}
Array filter will automatically remove falsey values for you, and you can include a callback should you need more flexability.

How to remove a specific empty array from $_SESSION with PHP?

I have set of arrays with combination of set/unset session value from the previous page. I want to remove the unset value. But I don't know how to remove it because it's have no key to tell which one.
$array
Array (
[4ltr] => 5
[] =>
[800ml] => 10
)
As you see the 2nd array is empty both key and value. I can thinking of the empty() but again, how to tell the script to remove the key with blank value?
Okey, I fxxk up. This is easy like shssst.
foreach ($_SESSION['ss'] as $key => $value) {
if (empty($value)) {
unset($_SESSION['ss'][$key]);
}
}
Another approach would be without assigning the modified data to a variable. It's just a fancy pattern. If you are doing that on every page then you can just write a global function to check.
array_walk($data, function($item, $key) use (&$data){
if(empty($item)){
unset($data[$key]);
}
});
print_r($data)
You can do it with,
$_SESSION= array_filter($_SESSION, function($v, $k){ return $v && $k;}, ARRAY_FILTER_USE_BOTH)
You can test below code, demo
print_r(array_filter(array('' => '2', '3' =>3), function($v, $k){ return $v && $k;}, ARRAY_FILTER_USE_BOTH));

How to get every key-value-pair from PHP-array

I need to get every key-value-pair from an array in PHP. The structure is different and not plannable, for example it is possible that a key contains an additional array and so on (multidimensional array?). The function I would like to call has the task to replace a specific string from the value. The problem is that the function foreach, each, ... only use the main keys and values.
Is there existing a function that has the foreach-function with every key/value?
There is not a built in function that works as you expect but you can adapt it using the RecursiveIteratorIterator, walking recursively the multidimensional array, and with the flag RecursiveIteratorIterator::SELF_FIRST, you would get all the elements of the same level first, before going deeper, not missing any pair.
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $key => $item) {
// LOGIC
}
The usual approach to this kind of task is using a recursive funcion.
Let's go step by step:
First you need the foreach control statement...
http://php.net/manual/en/control-structures.foreach.php
..that let you parse the associative array without knowing keys' names beforehand.
Then is_array and is_string (and eventually is_object, is_integer...) let you check the type of each value so you can act properly.
http://php.net/manual/en/function.is-array.php
http://php.net/manual/en/function.is-string.php
If you find the string to be operated then you do the replace task
If you find an array the function recalls itself passing the array just parsed.
This way the original array will be parsed down to the deepest level without missing and key-value pair.
Example:
function findAndReplaceStringInArray( $theArray )
{
foreach ( $theArray as $key => $value)
{
if( is_string( $theArray[ $key ] )
{
// the value is a string
// do your job...
// Example:
// Replace 'John' with 'Mike' if the `key` is 'name'
if( $key == 'name' && $theArray[ $key ] == "John" )
{
$theArray[ $key ] = "Mike";
}
}
else if( is_array( $theArray[ $key ] )
{
// treat the value as a nested array
$nestedArray = $theArray[ $key ];
findAndReplaceStringInArray( $nestedArray );
}
}
}
You can create a recursive function to treat it.
function sweep_array(array $array)
{
foreach($array as $key => $value){
if(is_array($value))
{
sweep_array($value);
}
else
{
echo $key . " => " . $value . "<br>";
}
}
}

php arrays: search for matching values in a table and replace with array keys

Please i want to loop through my table and compare values with an array in a php included file. If there is a match, return the array key of the matched item and replace it with the value of the table. I need help in returning the array keys from the include file and comparing it with the table values.
$myarray = array(
"12aaa"=>"hammer",
"22bbb"=>"pinchbar",
"33ccr"=>"wood" );
in my loop in a seperate file
include 'myarray.inc.php';
while($row = $db->fetchAssoc()){
foreach($row as $key => $val)
if $val has a match in myarray.inc.php
{
$val = str_replace($val,my_array_key);
}
}
So in essence, if my db table has hammer and wood, $val will produce 12aaa and 3ccr in the loop. Any help? Thanks a lot
You are looking for array_search which will return the key associated with a given value, if it exists.
$result = array_search( $val, $myarray );
if ($result !== false) {
$val = $result;
}
your array should look like
$myarray = array(
"hammer"=>"11aaa",
"pinchbar"=>"22bbb",
"wood"=>"33ccr" );
and code
if (isset($myarray[$key])){
//do stuff
}
I think you need the function in_array($val, $myarray);
If you don't want or can't change $myarray structure like #genesis proposed, you can make use of array_flip
include 'myarray.inc.php';
$myarray = array_flip($myarray);
while($row = $db->fetchAssoc()) {
foreach($row as $key => $val) {
if (isset($myarray[$val])) {
// Maybe you should use other variable instead of $val to avoid confusion
$val = $myarray[$val];
// Rest of your code
}
}
}

Multidimensional array in foreach

i want to do the foreach only if the content of myformdata[languages1][] is not empty (include zero)
I already try:
foreach((!empty($form['languages1']) as $val){
and
if (!empty($form['languages1'][])) {
foreach($form['languages1'] as $val){
//do stuff
}
i don't have any success. At the moment with the code below the loop is made when the input of myformdata[languages1][] is 0
foreach
foreach($form['languages1'] as $val){
//do stuff
}
thanks
foreach ( $form['languages1'] as $val )
{
// If the value is empty, skip to the next.
if ( empty($val) )
continue;
}
Reference: http://ca.php.net/continue
You're dealing with type coersion
You probably want something like
if(!empty($form['languages1']) && $form['languages1'] !== 0)
So that PHP will match 0 as a number, and not as false.

Categories