Foreach an array to check if the value of a key is not empty
I have an array that goes like this
$array = array('key1' => $_GET['value1'], 'key2' => $_GET['value2']);
I want to check if the key's value is not empty. Say a user goes to the webpage and requests this http://mysite.com/page.php?value1=somevalue&value2= which means that value2 is empty or say that it is missing from the query string i want to be able to check if it's there and is not empty.
I tried this
foreach($array as $key => $value)
{
if(empty($value))
{
//spout some error
}
}
but even though i enter this http://mysite.com/page.php?value1=somevalue meaning that value2 is missing, i don't get开发者_运维技巧 the error.
How do i achieve what i want?
When I do this:
<?php
$array = array('key1' => $_GET['value1'], 'key2' => $_GET['value2']);
foreach($array as $key => $value)
{
if(empty($value))
{
echo "$key empty<br/>";
}
else
{
echo "$key not empty<br/>";
}
}
?>
With:
http://jfcoder.com/test/arrayempty.php?value1=somevalue
EDIT: And this - http://jfcoder.com/test/arrayempty.php?value1=somevalue&value2=
I get:
key1 not empty
key2 empty
I'm thinking you need to give more context to your question about actual use, since there is probably some other detail throwing it off.
EDIT
This doesn't make any sense, but this was provided in a comment:
$array = array(
'key1' => '".mysql_real_escape_string($_GET['value1'])."',
'key2' => '".mysql_real_escape_string($_GET['value2'])."'
);
This actually doesn't parse due to the single quotes being mixed in with the single quoted string, and the fact that this, even if it did parse, would set the array piece equal to the literal string, not the function result.
I gather that maybe it was:
$array = array(
'key1' => "'".mysql_real_escape_string($_GET['value1'])."'",
'key2' => "'".mysql_real_escape_string($_GET['value2'])."'"
);
Which would indicate that a string would always be returned that was at least ''
, which would never be empty, due to the single quotes.
Consider PDO.
OH THIS WILL DO IT! this will add the value key pair to a new array.
if (isset($_GET)) {
$get_keys = array_keys($_GET);
foreach ($array_keys as $k) {
if ($_GET[$k] != '') {
$new_array[$k] = $_GET[$k];
}
}
}
Your foreach() loop is scanning only given values, not expected values. You need to define expected values and do a loop like this:
foreach($expected_keys as $key) {
if ( (!isset($array[$key])) || empty($array[$key]) ) {
//spout some error
}
}
I would check to see if the global $_GET var is set then loop through the values.
EDIT: PUSH GET VARS ONTO ARRAY IF THEY ARE SET (this will push the values onto an array and assign it value1, value2, etc.
if (isset($_GET)) {
foreach ($_GET as $get) {
if ($get != '') {
$new_array['value'.$i] = $get;
++$i;
}
}
}
empty() also performs an isset().
So if the key is missing, empty() won't cause an error. It validate as TRUE because it is empty
you would need to do a seperate isset() check to make sure the key is there
精彩评论