Jump to content

Checkboxes and arrays


tail

Recommended Posts

I'm working on a script to add users to a database. To set their permissions, I'm using checkboxes named news[], users[], etc. In my database, the permissions are set up as follows: "view,add,edit,delete". For example, in the news field, if a user can only view, add, and delete news, it would look like this: "1,1,0,1".

 

I'm using implode() to put the values into a string. However, if a box is not checked, it simply won't show up in the string instead of putting a "0" in it's spot. For example if I check view,edit,delete, the string will come up as "1,1,1" instead of the desired "1,0,1,1". My question is, how can I format the string to reflect the unchecked boxes? Thanks in advance for any help you may be able to give me!

Link to comment
https://forums.phpfreaks.com/topic/186804-checkboxes-and-arrays/
Share on other sites

OK so now I'm using in_array to see if the values exist in the array like this:

$news = $_POST['news'];
if (in_array(1,$news)) {
$perms = '1,';
} else {
$perms = '0,';
} if (in_array(2,$news)) {
$perms = $perms.'1,';
} else {
$perms = $perms.'0,';
} if (in_array(3,$news)) {
$perms = $perms.'1,';
} else {
$perms = $perms.'0,';
} if (in_array(4,$news)) {
$perms = $perms.'1';
} else {
$perms = $perms.'0';
}

 

But I feel there should be a more efficient way to do this (there are 8 different permission settings). Is there?

try this a bit long way around can be shortened but works with 4 permission sets

 

<?php
// view = 1,add = 2,edit = 3,delete = 4

$_POST['news'] = array(1,3,4); // comes in from post
echo getInsertString($_POST['news']);
function getInsertString($arr) {
$array = array_diff(array(1,2,3,4), $arr);
$array = array_fill_keys($array, 0);
$array_post = array_fill_keys($arr, 1);

$array_result = $array + $array_post;
ksort($array_result);

return implode(',', $array_result);
}



?> 

 

hope its helpful

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.