How do I put 1 variable in an array()? - php

I need to put a variable within an array.
For example.
$anarray = array("1","3","4");
foreach($anarray as $value){ // do such and such
I need the array() to include a variable instead. To be exact, I need it to contain a variable from my table in my database.
In effect, I would want my array to look like this.
Column 'example' in my users table contains - "1","3","4"
When I rewrite the code to look like this ...
$anarray = array($users['example']);
foreach($anarray as $value){ // do such and such
It doesn't work. What do I need to do to that variable to make it read the exact same as if it were the actual characters?

$anarray=array("1","2","3");
$new_array['example']=array();
for($i=0;$i<count($anarray);$i++){
array_push($new_array['example'],$anarray[$i]);
}

Related

Looping through array : New variable for each Value

Lets say I have an array looking like this:
$sql = array("name"=>"Peter", "active"=>1 , "age"=>30)
and a loop looking like this:
for($i=0;$i<count($sql);$i++){
$value[$i] = ($sql[$i]);
echo $value[$i];
}
I want the loop to iterate through the array and assign each value to a new variable.
In this code i tried to make it store the values in:
value1
value2
value3
But sadly this doesnt work, thus I am here seeking help.
Or is it a problem that i got an associative array instead of a numeric one?
I dont want to use this loop on this array only but on other arrays with different keys and length aswell.
Edit: I think I may have not wrote it cleary enough to tell you what i want to achieve:
I want to have three string values at the end of the loop not stored in an array:
Variable1 should contain "Peter"
Variable2 should contain "1"
Variable3 should contain "30"
Plus I want this loop to be dynamic, not only accepting this specific array but if I were to give it an array with 100 Values, I would want to have 100 different variables in which the values are stored.
Sorry for not being clear enough, I am still new at stackoverflow.
Going by your condition, assign each value to a new variable, I think what you want would be to use Variable variables. Here is an example:
<?php
$sql = array("name"=>"Peter", "active"=>1 , "age"=>30);
$count = 1;
foreach ($sql as $value) {
$x = 'value'.$count;
$$x = $value; //here's the usage of Variable variables
$count++;
}
echo $value1.'<br/>';
echo $value2.'<br/>';
echo $value3.'<br/>';
I went to your sample variables ($value1, $value2, etc.). I also changed your loop to foreach to easily loop the array. And I also added a $count that will serve as the number of the $value variable.
The $count wouldn't be necessary if your index are numeric, but since its an associative array, something like this is needed to differentiate the variables created
A brief explanation as requested:
$x contains the name of the variable you want to create (in this case, value1), then when you add another $ to $x (which becomes $$x), you are assigning value to the current value of $x (this equals to $value1='Peter')
To dynamically define a variable use $$. Demo
$sql = array("name"=>"Peter", "active"=>1 , "age"=>30);
$index = 1;
foreach($sql as $value){
${"value" . $index++} = $value;
}

Set PHP variable to MySQL data in foreach loop using array

I seem to have looked everywhere for this.
Here is the code i use to set a variable to a piece of data from a MySQL database
$PartNo=mysql_result($result,$i,"PartNo");
Where
$result = mysql_query("SELECT * FROM PriceList");
$i = 0, is added to by 1 every time my while loop restarts
PartNo is a field name in my MySQL table and also the name of the variable I want to set the data in the database to
PriceList is my database name
I want to loop through all the field names (the array has them) and set variables with the same names to that data. Like this:
$PartNo=mysql_result($result,$i,"PartNo");
$Group=mysql_result($result,$i,"Group");
$OnHand=mysql_result($result,$i,"OnHand");
$QOO=mysql_result($result,$i,"QOO");
$Description=mysql_result($result,$i,"Desc");
$Cost=mysql_result($result,$i,"Cost");
But with a foreach loop so it isn't as much code.
I was thinking something like this, but it won't execute no matter which way I go about it (parse_str, eval, exec, etc.)
$nDatabaseVars=array("PartNo","Group","OnHand","QOO","Desc","Cost");
foreach ($nDatabaseVars as $X) {
$$X=mysql_result($result,$i,'$X');
}
I need "$$X" to evaluate out so on the first iteration, it changes to $PartNo= and then sets $PartNo to whatever data is in the database on the first line. Which is what this part is: mysql_result($result,$i,"PartNo")
If I echo it out instead:
foreach ($nDatabaseVars as $X) {
echo "$$X=mysql_result($result,$i,'$X')";
}
I can get it to say exactly what I need executed ($PartNo=mysql_result($result,$i,"PartNo");) but not actually get the variable set.
You are passing a string containing "$X" to mysql_result, not the name of your column. Remove the single quotes:
$$X=mysql_result($result, $i, $X);
$$X=mysql_result($result,$i,'$X'); // these single quotes around $X avoid your actual string to be used.
$$X=mysql_result($result,$i,"$X");

Check field and rewrite to array Codeigniter

I need to truncate string and rewrite it back to array
I have got a function where I get data from data base
$data['about_text_list'] = $this->about_text_model->get_array();
I get these fields from data base : id, num, header, text, language
I need to strip_tags and truncate text with function word_limiter
foreach ($data['about_text_list'] as $items)
{
$data['about_text_list']['text'] = word_limiter($items['text'], 100);
$data['about_text_list']['text'] = strip_tags($items['text']);
}
in view I do foreach
<? foreach ($about_text_list as $line) : ?>
<td><?=$line['text']?></td>
<? endforeach; ?>
But I get error, please tell me how to do correct things like this...
In the loop in your controller, you're limiting the word count, then setting that to the value in the array. Then, you're overwriting that value with the strip_tags function. You're using both functions on the same value instead of using the altered values. (And I would strip the tags first, then limit the word count.)
You're also just overwriting the $data['about_text_list']['text'] value each iteration. I'm assuming this needs to be an array of 'text' values? I would create a new array with the updated content and merge your $data['about_text_list'] array with the new array.
Change that loop to this:
$newarray = array();
foreach ($data['about_text_list'] as $key => $value)
{
$item_text = $value['text'];
$altered = strip_tags($item_text);
$newarray[$key]['text'] = word_limiter($altered, 100);
}
$data['about_text_list'] = array_merge($data['about_text_list'], $newarray);
// here, you create a new empty array,
// then loop through the array getting key and value of each item
// then cache the 'text' value in a variable
// then strip the tags from the text key in that item
// then create a new array that mirrors the original array and set
// that to the limited word count
// then, after the loop is finished, merge the original and altered arrays
// the altered array values will override the original values
Also, I'm not sure what your error is (as you haven't told us), but make sure you're loading the text helper to give you access to the word_limiter function:
$this->load->helper('text');
Of course, this all depends on the structure of your array, which I'm guessing at right now.

PHP - Save value AND name using $_POST

I'm currently using the following format to save a value from an HTML form $item_name=$_POST['item_name'];
This saves the value, but how to I also save the name attribute in a variable?
Thanks in advance!
Assuming you want to store each element of $_POST variable as a key-value pair, then you can try:
$var = array();
foreach($_POST as $key => $val) {
$var[$key] = $val;
}
I'm saving a lot of values and want to avoid typing each one out.
Please, make your mind first.
Global variables are intended to be typed by hand.
If you want some automated processing - just keep them in a form of array.
Looks like rdt.exe's answer is what you're looking for.
maye you noticed you have to use the name to access the $_POST-array and get the value. if you want to store the name in a variable, too, just do:
$item_name_name = 'item_name';
$item_name_value = $_POST[$item_name_name];
you could also use some kind of loop to dynamically create variables with the according names like this:
foreach( $_POST as $name => $value ){
$$name = $value;
}
both ways are some kind of unnecessary and useless in my opinion, but you havn't stated what exactly you're trying to achive - so maybe this helps.
An alternative approach:
$keysarray = array_keys ( $_POST);
print_r( $keysarray);
This will give you all the keys in array
The function you are looking for is called extract.
This will create variables for all the $key=>$val pairs in the array.
$_EXAMPLE = array('bird' => 'chicken', 'dog' => 'greyhound');
export($_EXAMPLE);
echo $bird; # prints "chicken"
echo $dog; # prints "greyhound"
Watch out though - this is a huge security risk. So are the solutions described in some of the other answers.
The problem with doing something like this is that a user can tamper with the POST data, and set parameters other than the ones she is supposed to set. If they set variables that are actually variable names in your application, those variables can be overwritten.
$is_admin = false;
$_EXAMPLE = array('bird' => 'chicken', 'dog' => 'greyhound', 'is_admin' => 'true');
export($_EXAMPLE);
if ($is_admin) { # this will now evaluate to true.
# do sensitive stuff...
}

Extract MySQL fields of row into PHP variables and array

I have a table with a whole bunch of fields and records in it (40+fields).
I use my MySQL result like so:
<?php
$field1 = $row['field1'];
$field2 = $row['field2'];
$field3 = $row['field3'];
?>
As you see, the variable name is the same as the field name.
How can I do this for all fields, without having to type em all out? Would be really awesome for when I add more fields!
I know about the eval function, however I am not sure of how to use it in this case.
Also, how can I generate an array with the results? Like so:
<?php
$arr = array(
'field1'=>$row['field1']
);
?>
You can use extract():
extract($row);
However, take great care you don't pollute your namespace with this function. Say you already have a variable named $car, and you have a field in your database called car. You could be unwittingly overwriting your existing variables!
It may be safer, then, to use:
extract($row, EXTR_SKIP); // don't extract variables that already exist in the namespace
EDIT: In regards to your edit, you don't need to create an array for the results... your $row array is the result. If you construct the array as in your edit, $arr['field1'] = $row['field1'], so why not bypass the construction of this array altogether and just use the original $row?
The extract() function does exactly this:
extract($row);
By default it will override any existing variable (e.g. if you already have a field1 variable, it will override it). You can disable this by passing EXTR_SKIP as second parameter:
extract($row, EXTR_SKIP);
Or you can prefix all variables:
extract($riw, EXTR_PREFIX_ALL, 'row');
Also, how can I generate an array with the results?
$arr = $row;

Categories