0

Please consider the following PHP:

function get_ship_class()
{
    $csv = array_map("str_getcsv", file("somefile.csv", "r")); 
    $header = array_shift($csv); 

    // Seperate the header from data
    $col = array_search("heavy_shipping_class", $header); 

    foreach ($csv as $row)
    {      
        $array[] = $row[$col]; 
    }
}

How do I pass the resulting array from the above function into

if( in_array() ){
    //code
}

?

6
  • 1
    You have to return it, then pass the function call into it Commented Nov 22, 2018 at 14:06
  • in function you can use return $array; and the when you call get_ship_class() function you can retrieve your array Commented Nov 22, 2018 at 14:08
  • where did $array come from ? Commented Nov 22, 2018 at 14:10
  • @Andrew the function was borrowed from this answer. Is it incorrect? Commented Nov 22, 2018 at 14:12
  • 3
    @ptrcao I'm on mobile right now, seems like you've got a solid answer below :-) Commented Nov 22, 2018 at 14:26

2 Answers 2

7

A slightly abbreviated version, but the same as is being suggested is to return the required data from the function but using array_column() to extract the data...

function get_ship_class()
{
    $csv = array_map("str_getcsv", file("somefile.csv", "r")); 
    $header = array_shift($csv); 

    // Seperate the header from data
    $col = array_search("heavy_shipping_class", $header); 

    // Pass the extracted column back to calling method
    return array_column($csv,$col);
}

And to use it...

if ( in_array( "somevalue", get_ship_class() )) {
   //Process 
}

If you are going to use this returned value a few times, it may be worth storing it in a variable rather than passing it straight into the in_array() method.

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

Comments

1

This is the answer that the comments are suggesting.

function get_ship_class(){
    $array = array();
    $csv = array_map("str_getcsv", file("somefile.csv", "r")); 
    $header = array_shift($csv); 
    // Seperate the header from data    
    $col = array_search("heavy_shipping_class", $header); 
    foreach ($csv as $row) {      
    array_push($array, $row[$col]);
    // array_push($array, "$row[$col]"); // You may need it as a string instead.
    }
return $array;
}



if( in_array("whatever_you_are_looking_for", get_ship_class()) ){
//code
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.