0

I'm trying to make a PHP function that wraps around a variable that will check the variable value and change it if it matches another variable. I'm sure I'm doing it wrong, but...

Here's what I have so far:

<?php 

function Clear_Value(){

    $val='NONE';

    if(this== $val){ this=='';}

    };

$one    = 'One';
$two    = 'Two';
$three  = 'NONE';
$four   = 'Four';

Clear_Value($one);
Clear_Value($two);
Clear_Value($three);
Clear_Value($four);

echo $one.'<br>';
echo $two.'<br>';
echo $three.'<br>';
echo $four.'<br>';

?>

The output I'm going for would be:

One
Two

Four

I hope that's clear. I'm still learning functions in php so any pointers would be great.

Thanks

1
  • You can only use this (which should be $this) within a class. Commented Apr 23, 2012 at 17:33

3 Answers 3

3

You need to pass an argument by reference:

function Clear_Value(&$arg){

    if ($arg == 'NONE') $arg = '';
}

This way, the function can modify the variable's contents.

Live example: http://ideone.com/igHc5

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

3 Comments

This is a good approach (given current context) since this function can be used as a callback (i.e., array_map) instead of dealing with several variables.
That means you have two functions called Clear_Value() - remove your own one and just add this one.
Yeah, I did have two. Thanks! this is what I was after. So $arg could be anything, right? Also, what the PHP term for this so I can read up on it more?
1

what your constant this stands for?

you have to create some input variable in your function and use & prefix (refers to variable in memory)

function Clear_Value(&$var){

 $val='NONE';

 if($var == $val) 
  $var = '';

};

and another thing, if you want to change value of a variable, you use just single "=". i recommend you to see basics of syntax at php.net

sorry for my english

Comments

1

I am not sure what you expect here.

But when you execute this program it will show undefined variable error.

Try my sample changed code:-

 <?php 

   function Clear_Value($sam){

   $val='NONE';

   if($sam== $val){ $sam=='';}
   echo $sam.'<br>';

   };

   $one    = 'One';
   $two    = 'Two';
   $three  = 'NONE';
   $four   = 'Four';

   Clear_Value($one);
   Clear_Value($two);
   Clear_Value($three);
   Clear_Value($four);
   /*
   echo $one.'<br>';
   echo $two.'<br>';
   echo $three.'<br>';
   echo $four.'<br>';
   */
   ?>

Comments

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.