Jump to content

Getting variables from function


bill m

Recommended Posts

I'm pretty new to PHP and have been trying to get my head around it but I give up!! I'm missing something blatantly obvious when it comes to creating user defined functions but I don't know what.

 

I've got a multidimensional array to hold different values for dynamically creating pages:

<?php
//$var = array('file name' => array('title & link text', 'description', 'coma separated list of keywords')
$arr = array('home' => array('Home Page', 'a aa aaa.', 'z, zz, zzz.'),
             'about' => array('About Us', 'b bb bbb.', 'y, yy, yyy.'),
             'products' => array('Products', 'c cc ccc.', 'x, xx, xxx.'),
             'services' => array('Services', 'd dd ddd.', 'w, ww, www.'),
             'contact' => array('Contact Us', 'e ee eee.', 'v, vv, vvv.'),
             );
$key = array_keys($arr);
$val = array_values($arr);
?>

This works so I can echo or include different variables anywhere I want:

<?php
for ($i = 0; $i < count($key); $i++) {
  if (!isset($_GET['pg'])) { // default
    $x = $val[0][0];
    $y = $val[0][1];
    $z = $val[0][2];
    $inc = 'includes/'.$key[0].'.php';
  }   
  elseif ($_GET['pg'] == $key[$i]) { // link is selected
    $x = $val[$i][0];
    $y = $val[$i][1];
    $z = $val[$i][2];
    $inc = 'includes/'.$_GET['pg'].'.php'; 
  }
  elseif (!in_array($_GET['pg'], $key)) { // invalid URL
    $x = 'Error';
    $inc = 'includes/error.php';
    header('HTTP/1.0 404 Not Found');
    ob_start();
  }
}
$vars = array($x,$y,$z,$inc);

$title = $vars[0];
$desc = $vars[1];
$kw = $vars[2];
$cont = $vars[3];
?>

 

This doesn't:

<?php
function createContent($key, $val) {
  for ($i = 0; $i < count($key); $i++) {

... exact same code as above ...

  }
  $vars = array($x,$y,$z,$inc);
  return $vars;
}
?>
<?php
// Call function on page: 
createContent($key, $val);
$title = $vars[0];
$desc = $vars[1];
$kw = $vars[2];
$cont = $vars[3];
?>

 

I've spent days looking for an answer and trying to understand this. How are you supposed to get the variables to where you need them when you try to do all the 'good things' you're supposed to like "re-use", modularize, etc.

Link to comment
https://forums.phpfreaks.com/topic/47523-getting-variables-from-function/
Share on other sites

if you define variables in a function they only exist in this function. your function createContent returns a value, but you must store it in another variable.

so just replace the line

createContent($key, $val)

by

$vars=createContent($key, $val)

and it should work

Thanks Jove, that did the trick!

 

Just want to make sure I understand what is happening so I'm not tempted to take a baseball bat to my computer again. When I write a function, I need to return a variable and which stores the data inside the function. Doing this: createContent($key, $val) just runs the function without doing anything with the data, whereas doing this: $vars=createContent($key, $val) runs the function and stores the value of the variable returned inside the function in the new variable. (And the value depends on what is in the parenthesis in the function call).

<?php

$returnVal = returnValue(1); // $returnVal should be 2
print $returnVal . "<br />";

$extra = 1;
noReturnValue($extra); // $extra now equals 2
print $extra . "<br />";

$testVal = noValChange(3); // Nothing will be returned.
print $testVal . "<br />";

$ref = 2;
passByRef($ref); //$ref now equals 3;
print $ref; 

function returnValue($vals) {
     return $vals + 1;
}

function noReturnValue() {
     global $extra;
     $extra++;
     return;
}

function noValChange($vals) {
     // just do some process and do not return a value (IE MYSQL INSERT/DELETE)
     return;
}

function passByRef(&$vals) {
     $vals++;
     return;
}

?>

 

There you go.

Well it was working... until I broke it again. It seems to me that it shouldn't be necessary to add the variables for array_key() and array_val() like in the first post, and I could use an indexed array for the 2nd level in the array to simplify things a bit.

 

So the array now looks like this:

$arr = array(array('home','Home Page', 'a aa aaa.', 'z, zz, zzz,'),
             array(etc...

 

And in the function I altered the if/else statement by changing the keys for grabbing the different values:

if (!isset($_GET['id'])) { // default page
  $inc = "includes/{$arr[0][0]}.php";
  $x = $arr[0][1];
  $y = $arr[0][2];
  $z = $arr[0][3];
}
elseif ($_GET['id'] == $arr[$i][0]) { // link is selected
  $inc =  "includes/{$arr[$i][0]}.php"; 
  $x = $arr[$i][1];
  $y = $arr[$i][2];
  $z = $arr[$i][3];
}

 

All of which works fine... until I put in the last piece for defaulting to an error page

else { // invalid URL
  $inc = 'includes/error.php';
  $x = 'Error';
  $y = '';
  $z = '';
  ob_start();
  header('HTTP/1.0 404 Not Found');
}

 

Then regardless of which link is selected, I'm taken to the error page.

 

I've tried different ways of defining the condition for the elseif part, and shuffling things around, to no effect. Not sure why simplifying the array and reducing the number of variables affects the if/else like that, but it does. I would appreciate any help before giving up and going back to the old version.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.