Reputation: 3067
I have array
[Company] => Demo Company 1
[First Name] => Test
[Last Name] => Lead 1
[Designation] => This is testing title 1
[Email] => [email protected]
[Phone] => 242377
I used extract() function so all the index values will become variable names, I also used {} as there are spaces in variable names. But i dont know why its not working :( This ${'First Name'} returns blank...below is my code
foreach($vals as $value){
extract($value);
echo '<tr><td><a href="edit.php?id='.$LEADID.'">'.${'First Name'}.' '.${"Last Name"}.'</a></td><td>'.$Company.'</td><td>'.$Phone.'</td><td>'.$Email.'</td></tr>';
}
Upvotes: 0
Views: 653
Reputation: 2900
In this case you do not really need extract. You can use array indexes in interpolated strings.
$sample = array('name' => 'frank, 'age' => 42);
echo "{$sample['name']} is {$sample['age']} years old.";
If you can avoid using ${'strange names'} you should do it. If yo REALLY need to do it this way: Please update your question and tell us HOW $value is defined. Is vals The array from your first code block?
Upvotes: 0
Reputation: 91942
Variable names cannot contain spaces. For reference, read the manual on variables:
A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
If I were you, I'd just go with a shorter name on the array, so instead of $value
use $v
or similar. You can also use printf to make the code more readable:
foreach($vals as $v) {
printf('<tr><td><a href="edit.php?id=%d">%s %s</a></td><td>%s</td><td>%s</td><t\
d>%s</td></tr>',
$LEADID,
$v['First Name'],
$v['Last Name'],
$v['Company'],
$v['Phone'],
$v['Email']);
}
Upvotes: 6
Reputation: 71918
I think you should remove the spaces before using extract
:
$keys = str_replace( ' ', '', array_keys($vals));
$values = array_values($vals);
$vals = array_combine($keys, $values);
Then, after extract
you'd have variables like $FirstName
.
Upvotes: 1