soma56 Posted April 6, 2011 Share Posted April 6, 2011 I have several fields in a database in which some could be blank. I'd like to echo out 'Not Assigned' if that's the case. Based on my limited experience with PHP this is the way I'm going about it: if ($tech == "") { $tech = "Not Assigned"; } if ($crew == "") { $crew = "Not Assigned"; } if ($number == "") { $number = "Not Assigned"; } I'm pretty certain there is a way to simply place all of the variables into an array to determine if they are empty or not - Followed by changing the variable to 'Not Assigned' one time rather then repeating code over and over again. The way I'm doing it will work, however, something tells me there is a much more efficient way. Quote Link to comment https://forums.phpfreaks.com/topic/232890-very-basic-array-question/ Share on other sites More sharing options...
acefirefighter Posted April 6, 2011 Share Posted April 6, 2011 Something like this maybe? not sure if it is necessarily more efficient. Just run something like this in a while loop right after you pull the values from the database they will still be in an array. <?php $array = array( 'first' => 'John', 'middle' => '', 'last' => '' ); // this cycle echoes all associative array // key where value equals "apple" $i = 0; foreach ($array as $row) { // Fixed Problem with array position. if($i == false) { reset($array); $i ++; } // check for empty array values, echo and change value to not assigned if (empty($row)) { $key = key($array); echo $key.' is empty<br />'; $array[$key] = "Not Assigned"; } next($array); } foreach ($array as $row) { echo $row .' '; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/232890-very-basic-array-question/#findComment-1197825 Share on other sites More sharing options...
kenrbnsn Posted April 6, 2011 Share Posted April 6, 2011 You could do something like this: <?php $tmp = array('tech'=>$tech,'crew'=>$crew,'number'=>$number); foreach ($tmp as $f=>$v) { if ($v == '') { $tmp[$f] = 'Not Assigned'; } } ?> When you want to use the value, you would need to get the value from the array. Ken Quote Link to comment https://forums.phpfreaks.com/topic/232890-very-basic-array-question/#findComment-1197849 Share on other sites More sharing options...
acefirefighter Posted April 7, 2011 Share Posted April 7, 2011 You could do something like this: <?php $tmp = array('tech'=>$tech,'crew'=>$crew,'number'=>$number); foreach ($tmp as $f=>$v) { if ($v == '') { $tmp[$f] = 'Not Assigned'; } } ?> When you want to use the value, you would need to get the value from the array. Ken I like that. It is way better than what I came up with. Nice one. Quote Link to comment https://forums.phpfreaks.com/topic/232890-very-basic-array-question/#findComment-1198031 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.