Reputation: 3133
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
Upvotes: 0
Views: 3345
Reputation: 29160
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'];
Upvotes: 4
Reputation: 270599
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);
Upvotes: 3