Assign a value conditionally after array is set with PHP
If I wanted to do something like this:
<?php
$numbers = array(
"a_pos" => 0,
"b_pos" => 2,
"c_pos" => 3
);
if ($numbers["a_pos"] == 0)
$a_pos_txt = TRUE;
if ($numbers["b_pos"] == 0)
$开发者_运维问答b_pos_txt = TRUE;
if ($numbers["c_pos"] == 0)
$c_pos_txt = TRUE;
?>
(Just assign TRUE
to $a_pos_txt
because it is equal to 0
)
What would be that smart way to do it? I´m sure there must be a way to do it in "one step".
Thanks in advance!!
Please ask for any needed clarificarion.
Not really sure what you're trying to accomplish, as there may be a better approach overall, but to answer your question, you can skip the if
statements like so:
$a_pos_txt = $numbers["a_pos"] == 0;
$b_pos_txt = $numbers["b_pos"] == 0;
$c_pos_txt = $numbers["c_pos"] == 0;
If the $numbers is an array, you can do a loop to avoid repeating the similar pattern,
such as
foreach ($numbers as $key=>$val)
{
if ($val==0)
{
${$key."_txt"}=true;
}
}
精彩评论