onbids
onbids

Reputation: 53

Replace array-values through a Function

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";

Upvotes: 0

Views: 35

Answers (1)

MTK
MTK

Reputation: 3570

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);
?>

Upvotes: 2

Related Questions