0

Hello i want to pass array to my class function but i am not getting the value . plz help me out what is the problem with this sample code

 <?php
if(isset($_POST['submituser']))
{
$user = new User();
$user->connect();
$name=$_POST['name'];
$age=$_POST['age'];

$result = array($name=>$name,$age=>$age);


$user->setUser($result);

$user->disconnect();
}
?>

and the class function is like this

function setUser($result) 
{
echo $result[$name];
$errors_all = array();
$validate = new Validator();
$validate->addRequiredFieldValidator($result[$name],"First name is required.")."";
}

i can get by $result[0] by i want to get it by value Thanks

0

2 Answers 2

4

The way your code is written, if my name is Jay and I am 31 years old, the array will look like this...

{
'Jay' => 'Jay',
'31' => 31
}

The keys should be constant strings, and not (in this case) variables, as indicated by the $ sign.

Try this instead.

$result = array(
    'name'=>$name,
    'age'=>$age
);

This will yield

{
'name' => 'Jay',
'age' => 31
}

Important you must also change the way you are echo'ing your array values

//echo $result[$name];
echo $result['name'];
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot Man . Finally it worked after wasting 3 hrs ,Your solution worked perfectly
You're welcome. Please do see what you can do about visiting your old questions and accepting answers (by clicking the checkmark next to the correct answer). Otherwise, people will be hesitant to help you in the future. stackoverflow.com/users/592344/umar
3

When passing it, you should not have the $ in the array key. Instead they should be quoted strings:

// Incorrect:
$result = array($name=>$name,$age=>$age);

// Should be:
$result = array('name'=>$name,'age'=>$age);

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.