I'm trying to create a function in php that will read from an array. I am trying to concatenate text and the array id number, to read the value in the array, however it is the concatenated text that is being returned, not the value of the array.
Here is my code:
//arrays with words in dictionary
$dictionary_word1 = array("test1","test2","test3");
$dictionary_word2 = array("test4","test5","test6");
$dictionary_word3 = array("test7","test8","test9");
$word_to_lookup = "dictionary_word_1";
//value to send to function
$returned_word = convert_word($word_to_lookup);
//value returned from function
echo "<br>the returned word from the function is " . $returned_word;
//the text "$dictionary_word_1[2]" is displayed instead of array value
echo "<br>the value in the array is " . $dictionary_word1[2];
//this displays correcty as "test3"
function convert_word($word_to_convert)
{
global $dictionary_word1;
$converted_word = '$'.$word_to_convert .'[2]';
return $converted_word;
}
Could anyone give me any tips on where I am going wrong?
You need to reference the variable this way to do what you are trying (see PHP: Variable Variables and PHP: Variable Parsing):
$converted_word = ${$word_to_convert}[2];
However, notice the difference between dictionary_word_1 and $dictionary_word1? Won't work.
Regardless, anytime you're doing this you would be better with an array. In this case a multidimensional array. Consider:
$words[1] = array("test1","test2","test3");
$words[2] = array("test4","test5","test6");
$words[3] = array("test7","test8","test9");
Then you're always using $words just changing the index and then using a word from that array.
Related
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;
}
I'm trying to echo a simple json_encoded file.
<?php
$allMessages = file_get_contents("chatmessages.txt");
$allMessagesArr = explode(PHP_EOL, $allMessages);
$newObj = [];
var_dump($allMessagesArr);
foreach ($allMessagesArr as $thisLine) {
// echo($thisLine . "\n");
if (empty($thisLine) ) {
} else {
$thisLineArr = explode("|", $thisLine);
$newObj[trim($thisLineArr[0])] = trim($thisLineArr[1]);
// echo("here comes another one ".$thisLineArr[0] . " : ". $thisLineArr[1]."\n");
}
}
$newObjForFront = json_encode($newObj);
echo($newObjForFront);
chatmessages.txt looks like this
bob|hello
jimmy|second try incoming again
sam|third try
bob|oh damn
I've echoed each individual line within the loop and the fourth element appears. However, when I echo $newObjForFront, it's missing the last element. Any ideas why?
When you create your final array $newObj in
$newObj[trim($thisLineArr[0])] = trim($thisLineArr[1]);
Your using the name as the index to the array. As array indexes have to be unique, this means in fact the last entry overwrites the first one, so your actual output is...
{"bob":"oh damn","jimmy":"second try incoming again","sam":"third try"}
So it is in fact the first message that is missing.
Edit:
If you wanted to just have all of the messages, then you could store them using
$newObj[] = [ "user"=> trim($thisLineArr[0]), "msg" =>trim($thisLineArr[1])];
Which would give you the output as...
[{"user":"bob","msg":"hello"},{"user":"jimmy","msg":"second try incoming again"},{"user":"sam","msg":"third try"},{"user":"bob","msg":"oh damn"}]
$newObj[trim($thisLineArr[0])] = trim($thisLineArr[1]); this line will replace value with the last message of any username. if any username have multiple messages then only last message will be stored in the array.
By creating multidimensional you can store multiple messages with the same username. Check below code that may help you
$newObj[][trim($thisLineArr[0])] = trim($thisLineArr[1]);
Hard to phrase my question, but here goes. I've got a string like so: "13,4,3|65,1,1|27,3,2". The first value of each sub group (ex. 13,4,3) is an id from a row in a database table, and the other numbers are values I use to do other things.
Thanks to "Always Sunny" on here, I'm able to convert it to a multi-dimensional array using this code:
$data = '13,4,3|65,1,1|27,3,2';
$return_2d_array = array_map (
function ($_) {return explode (',', $_);},
explode ('|', $data)
);
I'm able to return any value using
echo $return_2d_array[1][0];
But what I need to be able to do now is search all the first values of the array and find a specific one and return one of the other value in i'ts group. For example, I need to find "27" as a first value, then output it's 2nd value in a variable (3).
You can loop through the dataset building an array that you can use to search:
$data = '13,4,3|65,1,1|27,3,2';
$data_explode = explode("|",$data); // make array with comma values
foreach($data_explode as $data_set){
$data_set_explode = explode(",",$data_set); // make an array for the comma values
$new_key = $data_set_explode[0]; // assign the key
unset($data_set_explode[0]); // now unset the key so it's not a value..
$remaining_vals = array_values($data_set_explode); // use array_values to reset the keys
$my_data[$new_key] = $remaining_vals; // the array!
}
if(isset($my_data[13])){ // if the array key exists
echo $my_data[13][0];
// echo $my_data[13][1];
// woohoo!
}
Here it is in action: http://sandbox.onlinephpfunctions.com/code/404ba5adfd63c39daae094f0b92e32ea0efbe85d
Run one more foreach loop like this:
$value_to_search = 27;
foreach($return_2d_array as $array){
if($array[0] == $value_to_search){
echo $array[1]; // will give 3
break;
}
}
Here's the live demo.
I used this but my array show blank.
foreach($page_data->result() as $text){ $i++;
echo $name="text".$i; //this line print ok.
$$name=array();
echo $$name['content']=$text->$content; //this line print ok.
print_r($text1);
} print_r($text1);
here i am tying to name the array dynamically as text1,text2,text3.......
but when i print $text1 it shows me a blank array.
can any one help me out with this.
It's simply a syntax ambiguity. $$name['content'] is understood as:
${$name['content']}
I.e. the name of the variable is supposed to be the value of $name['content'], which obviously doesn't exist, which actually leads to an error if you'd enable error reporting. You can solve this with:
${$name}['content'] = $text->$content;
However, you really should solve this by using an array instead of variable variables:
$texts[] = array('content' => $text->$content);
You're incrementing the index before you echo the contents of the variable, so if you only have 1 result, it will try and access an undefined index, you are also re initialising the name array every time you pass through the loop, you should not do this
Results
------------------
Num Content
0 I am a text post
If these were the results returned and you wanted to point to index i, then when your loop goes through this would happen:
i = 0;
i = 1;
assign values to name array
As there is only one result this would then happen
Results
------------------
Num Content
0 I am a text post
- - <----- i = 1 (null pointer exception?)
This would be why no values are showing in your array, try change your code to this:
// Declare i to point at the 0 index
$i = 0;
$name=array();
foreach($page_data->result() as $text){
$name[i]['content']=$text;
$i++;
}
Your name array will no add the text content to a new index with each pass of the loop, i.e. if you had 2 results
$name[0]['content'] = "This is a text post";
$name[1]['content'] = "Here is another post";
Hope this helps.
When sending data from a form to a second page, the value of the session is always with the name "Array" insteed of the expected number.
The data should get displayed in a table, but insteed of example 1, 2, 3 , 4 i get : Array, Array, Array.
(A 2-Dimensional Table is used)
Is the following code below a proper way to "call" upon the stored values on the 2nd page from the array ?
$test1 = $_SESSION["table"][0];
$test2 = $_SESSION["table"][1];
$test3 = $_SESSION["table"][2];
$test4 = $_SESSION["table"][3];
$test5 = $_SESSION["table"][4];
What exactly is this, and how can i fix this?
Is it some sort of override that needs to happen?
Best Regards.
You don't need any sort of override. The script is printing "Array" rather than a value, because you're trying to print to the screen a whole array, rather than a value within an array for example:
$some_array = array('0','1','2','3');
echo $some_array; //this will print out "Array"
echo $some_array[0]; //this will print "0"
print_r($some_array); //this will list all values within the array. Try it out!
print_r() is not useful for production code, because its ugly; however, for testing purposes it can keep you from pulling your hair out over nested arrays.
It's perfectly fine to access elements in your array by index: $some_array[2]
if you want it in a table you might do something like this:
<table>
<tr>
for($i = 0 ; $i < count($some_array) ; $i++) {
echo '<td>'.$some_array[$i].'</td>';
}
</tr>
</table>
As noted, try
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
That should show you what's in the session array.
A 2-dimensional table is just an array of arrays.
So, by pulling out $_SESSION["table"][0], you're pulling out an array that represents the first row of the table.
If you want a specific value from that table, you need to pass the second index, too. i.e. $_SESSION["table"][0][0]
Or you could just be lazy and do $table = $_SESSION["table"]; at which point $table would be your normal table again.
A nice way ...
<?php
foreach ($_SESSION as $key => $value) {
echo $key . " => " . $value . "<br>";
}
?>