0

I have a list of 14 variables that may or may not be empty. Let's say for example we have many individual variables that holds a select ingredient for a recipe. The number of ingredients in a recipe will differ by recipe, obviously. Is there a way, using PHP, that we can see how many of the 14 variables are not empty (i.e. contain an ingredient)?

Example (using 7 ingredients):

    $ing_1 = "carrots"
    $ing_2 = "apples"
    $ing_3 = "sugar"
    $ing_4 = "celery"
    $ing_5 = ""
    $ing_6 = ""
    $ing_7 = ""

How would I get the awnser 4?

Further Info:

I am using mysqli_fetch_array to load to variables.

6
  • if($ing_1 !== '') { // not empty} ................. Commented May 12, 2015 at 5:22
  • 1
    if you do this as an array - $ing[1]/$ing[2]/etc - instead of your var structure, then stackoverflow.com/questions/4422889/… or stackoverflow.com/questions/19696281/… or stackoverflow.com/questions/7672562/… could help. Commented May 12, 2015 at 5:22
  • Disclaimer: This is not PHP, but an alternative with (my)SQL: As you say, that you use mysqli_fetch_array I think you got a database in the back. You could select an addional field (count numbers of ingredients) and then just "read" this field where the number of ingredients is saved. Commented May 12, 2015 at 5:25
  • 1
    if you stay with your current var structure, then you could do a loop - $count=0; for($i=1;$i<=7;$i++){ if(!empty(${"ing_$i"})) $count++; } echo $count; Commented May 12, 2015 at 5:37
  • Please add your php code here.... Commented May 12, 2015 at 6:26

1 Answer 1

0

given your current variable structure, you could loop over your variable like-

$count=0; 
for($i=1;$i<=7;$i++){ 
    if(!empty(${"ing_$i"})) $count++; 
} 
echo $count;

with the $i<=7 could be increased to $i<=14 if you have 14 variable/ingredients.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.