April 24, 2012

What's wrong? I am receiving error msg: Invalid arguments passed in eval()

Question by user6919

I write down my php code:

<?php
        // 已有指定 material, 顯示 material 資訊
        if (strlen($m_id) > 0) {
            // 此 material 屬於哪些 mgroup
            $group_info = $mUtil->groupInfo($m_id);
            $group_names = array();
            foreach ($group_info as $mg_id => $row) {
                if (!$row["not_in_group"]) {
                    $group_names[] = $row["mg_name"];
                }
            }
        }
    ?>

  <table width="100%">
    <tr>
      <th colspan="2"><?php echo $m_name; ?></th>
    </tr>
    <tr class="odd">
      <th>Formula</th>
      <td width="80%"><?php echo $formula; ?></td>
    </tr>
    <tr class="odd">
      <th>Alias</th>
      <td><?php echo $alias; ?></td>
    </tr>
    <tr class="odd">
      <th>In groups</th>
      <!-- join() == implode() -->
      <td><?php echo join($group_names, ",&nbsp; "); ?></td>
    </tr>
  </table><br /><br />

but I get these error message:

Notice: Undefined variable: group_names in eval() (line 97 of D:xampphtdocsdrupalmodulesphpphp.module(80) : eval()'d code).
Warning: join() [function.join]: Invalid arguments passed in eval() (line 97 of D:xampphtdocsdrupalmodulesphpphp.module(80) : eval()'d code).
Notice: Undefined variable: group_names in eval() (line 97 of D:xampphtdocsdrupalmodulesphpphp.module(80) : eval()'d code).
Warning: join() [function.join]: Invalid arguments passed in eval() (line 97 of D:xampphtdocsdrupalmodulesphpphp.module(80) : eval()'d code).

Anyone can help me? Thanks a lot….

Answer by Starx

The undefined errors are due to variables like $group_names only being defined once

if (strlen($m_id) > 0) { ... } //condition is true.

Make sure the variable you are using are instantiated before using them.

Using isset($instancename) can be one of the ways to deal with this.

Example:

if(!isset($group_names)) $group_names = array();
// ^ if $group_names is not found then at least initialize it as an empty array
//   so that the rest of the script can go easy

Also, join() needs a glue to join the array, which is not in correct order.

<?php echo join(", ", $group_names); ?>

NOTE: The use of eval() has to be however be discouraged

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!