0

I have some trouble which I have no clue how to solve this. What I need is to replace values in non-associative array with a function and print out as variable.

function Confirm($var1)
{
    switch ($var1)
    {
        case 1:
            return "Gas";
            break;
        case 2:
            return "Soda";
            break;
        case 3:
            return "Air";
            break;
        case 4:
            return "Ice";
            break;
        case 5:
            return "Soft";
            break;

    }
}

$db_field_data = "1,2,3,5";

what i need is:

$field_data_trough_function = "Gas,Soda,Air,Soft";
4
  • Where is the "non-associative array" ??? Commented Jul 5, 2017 at 12:21
  • $db_field_data from database Commented Jul 5, 2017 at 12:26
  • So if is that would be like this: $db_field_data = [1,2,3,5]; ... 1,2,3,5 is a typo or would be 1,2,3,4,5 ? Commented Jul 5, 2017 at 12:29
  • its not typo, in db field is 1,2,3,4,5 stored Commented Jul 5, 2017 at 12:33

1 Answer 1

2

See coments inside code I have explained the steps

<?php


    function Confirm($var1)
    {
        switch ($var1)
        {
            case 1:
                return "Gas";
                break;
            case 2:
                return "Soda";
                break;
            case 3:
                return "Air";
                break;
            case 4:
                return "Ice";
                break;
            case 5:
                return "Soft";
                break;

        }
    }

    //array declaration can be $variable_name = []; or $variable_name = array() and not $variable_name = ""; that last is for string;

    //If you receive $db_field_data as string then you need first to convert an array with explode function on PHP
    //$db_field_data = "1,2,3,4,5";
    //$db_field_data = explode(",", $db_field_data);

    //if is array it need to be like this;
    $db_field_data = [1,2,3,4,5];

    //declare another array to store results inside
    $field_data_trough_function = [];

    //loop trough
    foreach( $db_field_data as $index => $val){
        //put to result array what function Confirm() returns
        $field_data_trough_function[] = Confirm($val);
    }

    //array
    echo "<pre>";
    print_r($field_data_trough_function);
    echo "</pre>";

    //or string
    echo implode(",", $field_data_trough_function);
?>
Sign up to request clarification or add additional context in comments.

2 Comments

yeah, that runs in javascript but i need it in php.thank you very much for this!!
Works like a charm! Thank you very much! You save me so much time! :)

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.