in_array based if/then/else statement
Im looking to create a conditional within an in_array statement. Basically, I would like to have a value (within div tags) returned for every key within an array which is outputted by Wordpress. In essence, Wordpress outputs keys from this array based on a checkbox dialog in the admin backend. So, if a key within the array is not found (because the administrator did not click it on in the checkb开发者_如何学JAVAox within the backend), than it will simply wont display it at all.
Here is the closest code I can ascertain as being what is needed. I decided that for testing purposes, I would temporarily have the words "Nope" returned if a key within the array is not there (rather than "simply not displaying it" as mentioned in the paragraph above).
$my_arr = get_custom_field('product_options');
$opts = array(
'Option 1' => '<div>Option 1 description</div>',
'Option 2' => '<div>Option 2 description</div>',
'Option 3' => '<div>Option 3 description</div>',
);
foreach($opts as $k=>$v) {
if (in_array($my_arr[$k],$opts)!==TRUE) echo $v; else echo 'nope';
}
?>
The above code has been tested and it does dispaly "Option __ description" for everything. It even displays "Option 2 description" when Option is not actually being outputted within the array (based off of the admin not clicking Option 2 within the backend). This is not correct and I wish to get it to (in this case for ease of testing) the echo within the "else" part of the above statement.
Update 2: Current code is here: http://codepad.org/nxzFUMMn
Update: Current code is here: http://codepad.org/iXVbmLGL
The trick here was to switch the arrays around, e.g.
<?php
$my_arr = get_custom_field('othermulti');
$opts = array(
'Man' => '<div>Man description</div>',
'Bear' => '<div>Bear description</div>',
'Pig' => '<div>Pig description</div>',
);
$opts_arr = array_keys($opts);
if ( is_array($my_arr) ) {
foreach($opts_arr as $opt) {
if ( in_array($opt, $my_arr) ) {
print $opts[$opt]; // will print the description for checked items.
}
else {
print $opt . ' was not checked.';
}
}
}
else {
print 'No options checked.';
}
?>
get_custom_field() is a custom template function for the plugin where this was used. See the following link for the details: http://wordpress.org/support/topic/ifelse-statement-for-custom-checkbox?replies=16
What is happening indicates that in fact none of the values of $my_arr
match a value of $opts
. I think you want to use
if (in_array($my_arr[$k], array_keys($opts)) !== TRUE) {
Also note that $my_arr[$k]
=== $v
and in_array($x, $y) !== TRUE
=== !in_array($x, $y)
精彩评论