t_machine Posted November 16, 2006 Share Posted November 16, 2006 Hi, I am wondering if anyone could help with this problem.I have an array that checks values in post and I would like to check if any of the post field is empty so I can let the user know that they can't post an empty field.I have the following$mycheck = array();$mycheck['one'] = $var1;$mycheck['two'] = $var2;$mycheck['three'] = $var3;Let's say $var3 is blank, how can I check the array and print that one of the field is empty?Thanks :) Link to comment https://forums.phpfreaks.com/topic/27484-how-to-check-if-value-in-array-is-empty/ Share on other sites More sharing options...
bqallover Posted November 16, 2006 Share Posted November 16, 2006 You can use the [url=http://uk2.php.net/manual/en/function.isset.php]isset()[/url] function to check if an array value has been set. Link to comment https://forums.phpfreaks.com/topic/27484-how-to-check-if-value-in-array-is-empty/#findComment-125644 Share on other sites More sharing options...
printf Posted November 16, 2006 Share Posted November 16, 2006 Without doing loops, you can use array_diff() inside another array_diff()...[code]<?php// array to check$check = array ( 'first_name' => 'Sonia', 'last_name' => '', 'age' => '', 'email' => '[email protected]' );// returns all the elements that are empty, using (trim) before testing$empty = array_diff ( $check, array_diff ( array_map ( 'trim', $check ), array ( '' ) ) );print_r ( $empty );?>[/code] Link to comment https://forums.phpfreaks.com/topic/27484-how-to-check-if-value-in-array-is-empty/#findComment-125652 Share on other sites More sharing options...
alpine Posted November 16, 2006 Share Posted November 16, 2006 If you are checking posted values from a form, this is a working example on how you can do that (remember to make the vars safe though)Example:[code]<?php$empty_arr = array();foreach($_POST as $fieldname => $fieldvalue){ if(empty($fieldvalue)) { $empty_arr[] = $fieldname." was left empty"; } ${$fieldname} = $_POST[$fieldname]; // <-- remember to make them safe using strip_tags, addslashes etc}if(!empty($empty_arr)){ echo "<ul><li>"; echo implode($empty_arr, '</li><li>'); echo "</li><ul>";}else{ // no empty fields, prosess posted values already defined as $fielnames}?>[/code] Link to comment https://forums.phpfreaks.com/topic/27484-how-to-check-if-value-in-array-is-empty/#findComment-125672 Share on other sites More sharing options...
t_machine Posted November 16, 2006 Author Share Posted November 16, 2006 Thanks everyone for the help :)alpine : Your script is perfect for what I need. Thanks :) Link to comment https://forums.phpfreaks.com/topic/27484-how-to-check-if-value-in-array-is-empty/#findComment-125727 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.