0

I've googled around and didn't see the answer. I have an array I'm storing in a variable that I'm trying to pass to a function..

$myArr = 'array('item1', 'item2')';

require('script.php'); //where actual function is

makeCode($myArr);

When I use makeCode(array('item1', 'item2')); it works fine.. I've even tried to add global $myArr to makeCode, but that didn't work either.

I'm thinking it's a scope problem, but maybe I'm misusing the string. print_r($myArr) prints properly, it just isn't passing or something.

The function basically just compares $myArr values and if it matches what's in the function's array, it outputs the correct HTML, so I didn't list it. It works, just not the variable.. Thanks!

--makeCode()--
 function makeCode($listArr){
 /* global $myArr; //Tried this */
   $output = '';
   $items = array(
      'item1'        =>  "Code for item1",
      'item2'         =>  "Code for item2"
       )
   /* $myArr = $listArr; //tried this too */
        foreach ($listArr as $val) {
            if(array_key_exists($val, $items)){
                if(strlen($output)>0) $output .="|"; //Add Sytnax
                $output .="$items[$val]";
            }
        }
  }

That's pretty much it.

1 Answer 1

4
$myArr = 'array('item1', 'item2')';

$myArr is a string here. I'm not sure that's what you meant. Try:

$myArr = array('item1', 'item2');

If this is what you meant then this will behave differently than calling

makeCode(array('item1', 'item2')); 

Because this is calling using an actual array.

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

12 Comments

Ah, I see. By doing that, it only loads the first item from the $myArr. What I need $myArr to do is output array('item1', 'item2') inside, just like it is on the last line in your post.
It does print Array ( [0] => item1 [1] => item2 ) however. Would I have to format this array? They're on the same page I just wanted to keep it up top with the rest of the overrides.
@kcdwayne I'm not sure I follow, maybe you could add the code for makeCode to your question along with what output you expect?
Sure. I've updated with the function. I'm just trying to get $myArr to work in makeCode() as makeCode($myArr) being the same as if I used makeCode(array('item1', 'item2')); . Right now the output completely disappears. (or just prints value 0 and skips the rest)
@kcdwayne There's a small bug in your method: foreach ($listArr as $val) is using $listArr but the start of the method uses $listArray
|

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.