2013-05-09 101 views
-3

比方說,我想檢查,看是否有變量是空的,然後做一些PHP援助......我可以這樣做:空()在一個循環中

if (empty($phone)) { $phone = 'Not Provided'; } 

但我想這樣做一堆物品。所以我想這樣的數組和一個循環,所以東西:

$optionalFieldsArray = array($phone, $address, $city, $state, $zip); 

foreach ($optionalFieldsArray as $value) { 
     //what goes here???? 
    } 

這是一個的foreach合理的方式做到這一點,在那裏我可以檢查是否$電話,地址$,$城市等都是清空並分配「未提供」字符串,當它是?

如果是這樣,有人可以幫助我使用循環內部的語法嗎?

+0

爲什麼downvote? – 2013-05-09 17:29:41

+0

這很容易googleable – 2013-05-09 17:40:51

+0

是啊,好吧,我沒有找到合適的答案。我想你比我好。 – 2013-05-09 17:47:56

回答

3

,你可以這樣做此:

<?php 

$required_vars = array('phone', 'address', 'city', 'state', 'zip'); 
foreach($required_vars as $required_var) { 
    if(empty($$required_var)) 
     $$required_var = 'Not Provided'; // $$var -> variable with name = value of $var 
} 

?> 

檢查上面的代碼自己。那麼只有你可以理解它是如何工作的。因爲這是混淆概念。

+1

爲什麼變量變量? – 2013-05-09 17:36:00

+0

他想檢查給定數組中列出的某些變量。所以我們遍歷數組並檢查名爲current-array-element-value的變量 – 2013-05-09 17:43:14

+0

,應該自己檢查它(如果不知道)。那麼只有他能理解它是如何工作的。因爲它很混亂。 – 2013-05-09 17:45:19

3
$optionalFieldsArray = array('phone'=>$phone, 'address'=>$address, 'city'=>$city, 'state'=>$state, 'zip'=>$zip); 

foreach ($optionalFieldsArray as $key => $value) { 
    if (empty($value)) { $optionalFieldsArray[$key] = 'Not Provided'; } 
} 

echo "<pre>"; 
print_r($optionalFieldsArray); 
echo "</pre>"; 
0

我會這樣說 -

$optionalFieldsArray = array($phone, $address, $city, $state, $zip); 

foreach ($optionalFieldsArray as $key => $value) { 
     if (empty($optionalFieldsArray[$key])) { 
      $optionalFieldsArray[$key] = 'Not Provided'; 
     } 
} 
0

結合您提供的兩個代碼示例,並使用字符串作爲可選的陣列中的鍵:

$optional = array(
    'phone' => $phone, 
    'address' => $address, 
    'city' => $city, 
    'state' => $state, 
    'zip'  => $zip, 
); 
foreach ($optional as $type => $value) { 
    if ($value == null) { 
     echo "The {$type} field is empty!<br>"; 
    } 
} 
0
$optionalFieldsArray = array($phone, $address, $city, $state, $zip); 

foreach($optionalFieldsArray as $k => $v) { 
    // you could check for !empty here if you wanted too 
    $optionalFieldsArray[$k] = empty($v) ? 'Not Provided' : $v; 
} 

print_r($optionalFieldsArray); 

Input Vars: 
$phone = "1234567899"; 
$address = ""; 
$city = ""; 
$state = ""; 
$zip = ""; 
Output: 
Array ([0] => 1234567899 [1] => Not Provided [2] => Not Provided [3] => Not Provided [4] => Not Provided)