I need to compare 2 arrays one from database with available cloth Sizes
and a default Size
$sizedefault = array('s','m','l','xl','xxl','xxxl','xxxxl','xxxxxl'); // Default Sizes
$sizeavailable = explode(',',$pd_size); // Available Sizes (db) s,m,l,xl
$available = array_diff($sizedefault , $sizeavailable );
$notavailable = array_intersect($sizeavailable , $sizedefault);
$output = "";
foreach ($notavailable as $value){
$output .= "<input type=\"checkbox\" name=\"size[]\" id=\"$value\" value=\"$value\" checked=\"checked\"/><label for=\"$value\">".$value."</label>";
}
foreach($available as $value){
$output .= "<input type=\"checkbox\" name=\"size[]\" id=\"$value\" value=\"$value\" /><label for=\"$value\">".$value."</label>";
}
that works so far but, the output is not sorted after i check eg: “xxxxl” and submit/request
i get this result: (x) = checked
s(x) m(x) l(x) xl(x) xxxxl(x) xxxxxl() xxl()
how can i keep them sorted as $sizedefault?
s(x) m(x) l(x) xl(x) xxl() xxxxl(x) xxxxxl()
It is not necessary to build those arrays beforehand – you could use
in_array()to check for the value’s existence in the availability array while your loop runs. It’s better also because you don’t have to duplicate the HTML code for your checkbox, the only difference is the presence of thechecked="checked"and you can add that conditionally.If
$sizedefaultcomes from an external source (eg. a user, cookie, anything like that), or came from an external source previously before saving to the database, you should also escape the values inside it before printing it into HTML. You can do that withhtmlspecialchars(). Otherwise people would be able to inject scripts into your HTML.