Better way to unset multiple array elements - php

The deal here is that I have an array with 17 elements. I want to get the elements I need for a certain time and remove them permanently from the array.
Here's the code:
$name = $post['name'];
$email = $post['email'];
$address = $post['address'];
$telephone = $post['telephone'];
$country = $post['country'];
unset($post['name']);
unset($post['email']);
unset($post['address']);
unset($post['telephone']);
unset($post['country']);
Yes the code is ugly, no need to bash. How do I make this look better?

Use array_diff_key to remove
$remove = ['telephone', 'country'];
$remaining = array_diff_key($post, array_flip($remove));
You could use array_intersect_key if you wanted to supply an array of keys to keep.

It looks like the function extract() would be a better tool for what you're trying to do (assuming it's extract all key/values from an array and assign them to variables with the same names as the keys in the local scope). After you've extracted the contents, you could then unset the entire $post, assuming it didn't contain anything else you wanted.
However, to actually answer your question, you could create an array of the keys you want to remove and loop through, explicitly unsetting them...
$removeKeys = array('name', 'email');
foreach($removeKeys as $key) {
unset($arr[$key]);
}
...or you could point the variable to a new array that has the keys removed...
$arr = array_diff_key($arr, array_flip($removeKeys));
...or pass all of the array members to unset()...
unset($arr['name'], $arr['email']);

There is another way which is better then the above examples.
Source: http://php.net/manual/en/function.unset.php
Instead of looping thorough the entire array and unsetting all its keys, you can just unset it once like so:
Example Array:
$array = array("key1", "key2", "key3");
For the entire array:
unset($array);
For unique keys:
unset($array["key1"]);
For multiple keys in one array:
unset($array["key1"], $array["key2"], $array["key3"] ....) and so on.
I hope this helps you in your development.

I understand this question is old, but I think an optimal way might be to do this:
$vars = array('name', 'email', 'address', 'phone'); /* needed variables */
foreach ($vars as $var) {
${$var} = $_POST[$var]; /* create variable on-the-fly */
unset($_POST[$var]); /* unset variable after use */
}
Now, you can use $name, $email, ... from anywhere ;)
NB: extract() is not safe, so it's completely out of question!

<?php
$name = $post['name'];
$email = $post['email'];
$address = $post['address'];
$telephone = $post['telephone'];
$country = $post['country'];
$myArray = array_except($post, ['name', 'email','address','telephone','country']);
print_r($myArray);
function array_except($array, $keys){
foreach($keys as $key){
unset($array[$key]);
}
return $array;
}
?>

In php unset function can take multiple arguments
$test = ['test1' => 1, 'test2' => 4, 'test34' => 34];
unset($test['test1'], $test['test34']);
Here is this description from documentation
unset(mixed $var, mixed ...$vars): void

Related

PHP $_POST array

I'm building a webhook that will receive data from an external service.
In order to retrieve data, I'm using the following array:
$data = [
$_POST['aaa'],
$_POST['bbb'],
$_POST['ccc'],
$_POST['ddd'],
$_POST['eee']
];
Is it possible to build the same array without repeating $_POST? I mean something like:
$data = $_POST [
['aaa'],
['bbb'],
['ccc'],
['ddd'],
['eee']
];
Obviously, that code is wrong.
Thanks.
There's no shortcut like that. You could use array_map():
$data = array_map(function($key) {
return $_POST[$key];
}, ['aaa', 'bbb', 'ccc', ...]);
$data = $_POST
This will build your new $data array the same way as your GLOBAL $_POST array including the POST Key names and their assigned values.
Also checkout extract($_POST), as this will extract each key to its same name variable, which may be easier to then reference in your web-hook or any functions or procedural code you uses from then on. This essentially does this:
$aaa = $POST['aaa']
$bbb = $POST['bbb']
$ccc = $POST['ccc']
etc etc
https://www.php.net/manual/en/function.extract.php
The simplest way for me would be:
For getting all the values in the $_POST array
foreach($_POST as $value){
$data[] = $value;
}
For getting all the values and want to keep the key
foreach($_POST as $key=>$value){
$data[$key] = $value;
}
For getting a specific array of values from the array
foreach(['aaa','bbb','ccc','ddd','eee'] as $column){
$data[] = $_POST[$column];
}
Just a good idea to always escape variables ;)
$con = mysqli_connect('hostcleveranswer.com','USERyouearn','PWDanupv0Te','dropthemicDB')
foreach($_POST as $key => $value) {
$data[] = mysqli_escape_string($con,$value);
}
//i feel that was a good simple answer using tools without having to a learn a new function syntax

PHP Unify duplicate array

in my PHP code I have many array like this:
0 = ['attr_id':1,'name':'qty','value':'100'];
1 = ['attr_id':1,'name':'qty','value':'200'];
2 = ['attr_id':1,'name':'qty','value':'500'];
3 = ['attr_id':2,'name':'price','value':'10$'];
I want merge this array like this:
0 = ['attr_id':1,'name':'qty','value':['100','200','500']];
1 = ['attr_id':1,'name':'price','value':'10$'];
can you guys help me please?
thanks
This should be simpler. Build the result using the attr_id as the index and append the value:
foreach($array as $values) {
$result[$values['attr_id']]['value'][] = $values['value'];
$result[$values['attr_id']] = $result[$values['attr_id']] + $values;
}
If you need to reindex, just use array_values() on the $result.
This is one method where you loop through an array_column array of the id's and use key to insert values from values array.
$value = array_column($arr, 'value');
$id = array_column($arr, 'attr_id');
$res =[];
Foreach($id as $key => $i){
If(!isset($res[$i])) $res[$i] = ['attr_id' => $i, 'name'=>'qty', 'value' => []];
$res[$i]['value'][] = $value[$key];
}
Var_dump($res);
https://3v4l.org/VXI5E
As you see I use the id as key to keep track of the result array.
If you want to clear this, meaning reset the counting from 0, use array_values.
$res = array_values($res);
Edit: also the 10$ is inside an array in my answer, this makes it easier to use the array later in my opinion.
If you must save it as an string I can fix it, but it will probably be harder to use the array later with a mixed item.

How Can I Select Data by Name From Array in PHP?

I have an array like this:
Array(
[0]=>Array([uploaderName]=>x[uploadedImageName]=>k6gIjfO[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[1]=>Array([uploaderName]=>x[uploadedImageName]=>byUTyJo[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[2]=>Array([uploaderName]=>x[uploadedImageName]=>oSVEnNk[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[3]=>Array([uploaderName]=>x[uploadedImageName]=>Dj7GRYS[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[4]=>Array([uploaderName]=>x[uploadedImageName]=>upsb8IC[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[5]=>Array([uploaderName]=>x[uploadedImageName]=>YoEEzGi[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[6]=>Array([uploaderName]=>x[uploadedImageName]=>st3dLNs[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[7]=>Array([uploaderName]=>x[uploadedImageName]=>LBNpiIG[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[8]=>Array([uploaderName]=>x[uploadedImageName]=>mFYDmBG[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
[9]=>Array([uploaderName]=>x[uploadedImageName]=>z03kSx1[uploaderIp]=>195.155.116.217[uploader]=>e0699587cbfd[uploadedServer]=>alpha)
)
I want to get any image's data from this array.
Example: When user shows uploadedImageName == jCPjeWv, I wan't to get who is it's uploader.
Simple, just use foreach
$arr = array(/* content here */);
foreach($arr as $value){
if($value['uploadedImageName'] == 'jCPjeWv'){
echo $value['uploaderName'];
break;
}
}
Just for fun, here's another way:
echo array_column($array, 'uploaderName', 'uploadedImageName')['jCPjeWv'];
Get an array of uploaderName with the index set to uploadedImageName
Access the index using the uploadedImageName 'jCPjeWv'
Obviously to do it multiple times you would want to actually create a new array:
$images = array_column($array, 'uploaderName', 'uploadedImageName');
echo $images['jCPjeWv'];
If you want to access the other values as well, then use null instead of uploaderName:
$images = array_column($array, null, 'uploadedImageName');
echo $images['jCPjeWv']['uploaderName'];
echo $images['jCPjeWv']['uploaderIp'];
NOTE: These ways only work if the uploadedImageName is unique.
A foreach is possible, but I think it's important to learn the array functions as well so I'm just going to put this example here.
$uploadedImageName = 'jCPjeWv';
$filtered = array_filter($array, function($value) use ($uploadedImageName) {
return ($value['uploadedImageName'] == $uploadedImageName);
});
This will return a $filtered with the other arrays removed since their $value['uploadedImageName'] will not equal $uploadedImageName.
For more info check out the http://php.net/manual/en/function.array-filter.php manual.

Unset multiple intems in array

Is there a PHP built-in function to unset multiple array items by key?
That would be a native equivalent of:
foreach($badElements as $k) {
unset($allElements[$k]);
}
or, even better:
$keys = array_keys($badElements);
foreach($keys as $k) {
unset($allElements[$k]);
}
The following doesn't fullfill your requirement in complete since it's not in-situ. But maybe you're ok with copying the array:
$v = array("lol"=>"blub", "lal"=>"blab", "lulz"=>"gagh");
$k = array("lol", "lulz");
var_dump(array_diff_key($v, array_flip($k)));
[ run it on codepad ]
You could create an array of the keys you want to remove and loop through, explicitly unsetting them.
Examples:
$removeKeys = array('name', 'email');
foreach($removeKeys as $key) {
unset($badElements[$key]);
}
Or you could point the variable to a new array that has the keys removed.
$badElements = array_diff_key($badElements, array_flip($removeKeys));
or pass all of the array members to unset().
unset($badElements['name'], $badElements['email'])

Make 1d Array from 1st member of each value in 2d Array | PHP

How can you do this? My code seen here doesn't work
for($i=0;i<count($cond);$i++){
$cond[$i] = $cond[$i][0];
}
It can be as simple as this:
$array = array_map('reset', $array);
There could be problems if the source array isn't numerically index. Try this instead:
$destinationArray = array();
for ($sourceArray as $key=>$value) {
$destinationArray[] = $value[0]; //you may want to use a different index than '0'
}
// Make sure you have your first array initialised here!
$array2 = array();
foreach ($array AS $item)
{
$array2[] = $item[0];
}
Assuming you want to have the same variable name afterwards, you can re-assign the new array back to the old one.
$array = $array2;
unset($array2); // Not needed, but helps with keeping memory down
Also, you might be able to, dependant on what is in the array, do something like.
$array = array_merge(array_values($array));
As previously stated, your code will not work properly in various situation.
Try to initialize your array with this values:
$cond = array(5=>array('4','3'),9=>array('3','4'));
A solution, to me better readable also is the following code:
//explain what to do to every single line of the 2d array
function reduceRowToFirstItem($x) { return $x[0]; }
// apply the trasnformation to the array
$a=array_map('reduceRowTofirstItem',$cond);
You can read the reference for array map for a thorough explanation.
You can opt also for a slight variation using array_walk (it operate on the array "in place"). Note that the function doesn't return a value and that his parameter is passed by reference.
function reduceToFirstItem(&$x) { $x=$x[0]; }
array_walk($cond, 'reduceToFirstItem');
That should work. Why does it not work? what error message do you get?
This is the code I would use:
$inArr;//This is the 2D array
$outArr = array();
for($i=0;$i<count($inArr);$i++){
$outArr[$i] = $inArr[$i][0];
}

Categories