How to remove a specific empty array from $_SESSION with PHP? - 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));

Related

How to reset array index after unset key in foreach loop in php?

I am using unset to remove the particular object from the array with my conditions. But after unset, I am getting an object rather than an array. I tried to use array_values to rearrange the index, but it's not working for me. Please help me to resolve this issue. Below is my code:
$empId = '100'; //just for example.
foreach($jsonData['data'] => $key as $value){
if($value['emp_id'] == $empId){
unset($jsonData['data][$key]);
}
}
after loop code//
return $jsonData;
after unset data, it gives me an object. I tried with array_values, array_merge but it's not working for me.
I tried to replace array_splice with unset, but it's not removing data.
You have at least 2 serious syntax errors in your code.
This is what it should look like:
<?php
// Some dummy data
$empId = '100';
$jsonData = [];
$jsonData['data'] = [
'key' => ['emp_id' => 'value'],
'key2' => ['emp_id' => '100']
];
// Fixed foreach loop
foreach($jsonData['data'] as $key => $value) {
if ( $value['emp_id'] == $empId ) {
unset( $jsonData['data'][ $key ] );
}
}
print_r($jsonData);
key emp_id is as string, not as index.
your code has unset emp_id.
alternatively, you may use array_map function and then use array_values to reindex your array.

How to delete value from mupltiple array using key in 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

Change $key of associative array in a foreach loop in php

I have an array like this:
array(
'firstName' => 'Joe',
'lastName' => 'Smith'
)
I need to loop over every element in my array and in the end, the array should look like this:
array(
'FirstName' => 'Joe',
'LastName' => 'Smith'
)
Failed idea was:
foreach($array as $key => $value)
{
$key = ucfirst($key);
}
This obviously will not work, because the array is not passed by reference. However, all these attempts also fail:
foreach(&$array as $key => $value)
{
$key = ucfirst($key);
}
foreach($array as &$key => $value)
{
$key = ucfirst($key);
}
Pretty much at my wits end with this one. I'm using Magento 1.9.0.1 CE, but that's pretty irrelevant for this problem. If you must know, the reason I have to do this is because I have a bunch of object that's I'm returning as an array to be assembled into a SOAP client. The API I'm using requires the keys to begin with a capital letter...however, I don't wish to capitalize the first letter of my object's variable names. Silly, I know, but we all answer to someone, and that someone wants it that way.
unset it first in case it is already in the proper format, otherwise you will remove what you just defined:
foreach($array as $key => $value)
{
unset($array[$key]);
$array[ucfirst($key)] = $value;
}
You can't modify the keys in a foreach, so you would need to unset the old one and create a new one. Here is another way:
$array = array_combine(array_map('ucfirst', array_keys($array)), $array);
Get the keys using array_keys
Apply ucfirst to the keys using array_map
Combine the new keys with the values using array_combine
The answers here are dangerous, in the event that the key isn't changed, the element is actually deleted from the array. Also, you could unknowingly overwrite an element that was already there.
You'll want to do some checks first:
foreach($array as $key => $value)
{
$newKey = ucfirst($key);
// does this key already exist in the array?
if(isset($array[$newKey])){
// yes, skip this to avoid overwritting an array element!
continue;
}
// Is the new key different from the old key?
if($key === $newKey){
// no, skip this since the key was already what we wanted.
continue;
}
$array[$newKey] = $value;
unset($array[$key]);
}
Of course, you'll probably want to combine these "if" statements with an "or" if you don't need to handle these situations differently.
This might work:
foreach($array as $key => $value) {
$newkey = ucfirst($key);
$array[$newkey] = $value;
unset($array[$key]);
}
but it is very risky to modify an array like this while you're looping on it. You might be better off to store the unsettable keys in another array, then have a separate loop to remove them from the original array.
And of course, this doesn't check for possible collisions in the aray, e.g. firstname -> FirstName, where FirstName already existed elsewhere in the array.
But in the end, it boils down to the fact that you can't "rename" a key. You can create a new one and delete the original, but you can't in-place modify the key, because the key IS the key to lookup an entry in the aray. changing the key's value necessarily changes what that key is pointing at.
Top of my head...
foreach($array as $key => $value){
$newKey = ucfirst($key);
$array[$newKey] = $value;
unset($array[$key]);
}
Slightly change your way of thinking. Instead of modifying an existing element, create a new one, and remove the old one.
If you use laravel or have Illuminate\Support somewhere in your dependencies, here's a chainable way:
>>> collect($array)
->keys()
->map(function ($key) {
return ucfirst($key);
})
->combine($array);
=> Illuminate\Support\Collection {#1389
all: [
"FirstName" => "Joe",
"LastName" => "Smith",
],
}

Adding key=>value pair to existing array with condition

Im trying to add a key=>value to a existing array with a specific value.
Im basically looping through a associative array and i want to add a key=>value foreach array that has a specific id:
ex:
[0] => Array
(
[id] => 1
[blah] => value2
)
[1] => Array
(
[id] => 1
[blah] => value2
)
I want to do it so that while
foreach ($array as $arr) {
while $arr['id']==$some_id {
$array['new_key'] .=$some value
then do a array_push
}
}
so $some_value is going to be associated with the specific id.
The while loop doesn't make sense since keys are unique in an associative array. Also, are you sure you want to modify the array while you are looping through it? That may cause problems. Try this:
$tmp = new array();
foreach ($array as $arr) {
if($array['id']==$some_id) {
$tmp['new_key'] = $some_value;
}
}
array_merge($array,$tmp);
A more efficient way is this:
if(in_array($some_id,$array){
$array['new_key'] = $some_value;
}
or if its a key in the array you want to match and not the value...
if(array_key_exists($some_id,$array){
$array['new_key'] = $some_value;
}
When you use:
foreach($array as $arr){
...
}
... the $arr variable is a local copy that is only scoped to that foreach. Anything you add to it will not affect the $array variable. However, if you call $arr by reference:
foreach($array as &$arr){ // notice the &
...
}
... now if you add a new key to that array it will affect the $array through which you are looping.
I hope I understood your question correctly.
If i understood you correctly, this will be the solution:
foreach ($array as $arr) {
if ($arr['id'] == $some_id) {
$arr[] = $some value;
// or: $arr['key'] but when 'key' already exists it will be overwritten
}
}

Removing an element from an array (PHP)

I want to remove an element from a PHP array (and shrink the array size). Just looking at the PHP docs, it seems this can be done using array_slice() and array_merge()
so I am guessing (off the top of my head) that some combination of array_merge() and array_slice will work. However, array_slice() requires an index (not a key), so I'm not sure how to quickly cobble these functions together for a solution.
Has anyone implemented such a function before?. I'm sure it must be only a few lines long, but I cant somehow get my head around it (its been one of those days) ...
Actually, I just came up with this cheesy hack when writing up this question....
function remove_from_array(array $in, value) {
return array_diff($in, (array)$value);
}
too ugly? or will it work (without any shocking side effects)?
This functionality already exists; take a look at unset.
http://php.net/manual/en/function.unset.php
$a = array('foo' => 'bar', 'bar' => 'gork');
unset($a['bar']);
print_r($a);
output will be:
array(
[foo] => bar
)
There's the array_filter function that uses a callback function to select only wanted values from the array.
you want an unset by value. loop through the array and unset the key by value.
unset($my_array['element']);
Won't work?
This code can be replaced by single array_filter($arr) call
foreach($array as $key => $value) {
if($value == "" || $value == " " || is_null($value)) {
unset($array[$key]);
}
}
/*
and if you want to create a new array with the keys reordered accordingly...
*/
$new_array = array_values($array);

Categories