So I have a string with comma separated values:
$accounts = "1,2,3,4,5,6";
And I want to reverse that order. So I wrote this:
$accountsrev = implode(',',rsort(explode(',',$accounts)));
Basically I convert to an array, reverse the array, and implode it back into a string. What's wrong with that?
I get a load of errors like this:
Strict Standards: Only variables should be passed by reference in /home/username/public_html/file.php on line 121
Warning: implode(): Invalid arguments passed in /home/username/public_html/file.php on line 121
Edit:
Now I wonder if the way I build the $accounts variable is wrong. I pull 7 rows from the database and then build the $accounts variable in a while loop. The id is an integer in the database:
$accounts = '';
$i = 1;
while ($data = $getdata->fetch(PDO::FETCH_ASSOC)) {
if ($i < 7) {
$accounts .= $data['id'].',';
} else {
$accounts .= $data['id'];
}
$i++;
}
Does the way I make the $accounts variable not produce a string?
This is just something that tells you you're doing something completely wrong:
$array = [1,2,3,4];
rsort($array);
//$array is sorted.
However:
rsort(array_filter($array));
//Array filter returned a copy of the original array so $array is neither sorted nor filtered.
You need to do:
$accounts = '';
while ($data = $getdata->fetch(PDO::FETCH_ASSOC)) {
$accounts .= $data['id'].',';
}
$accountsrev = explode(',',rtrim($accounts,","));
rsort($accountsrev);
$accountsrev = implode(',',$accountsrev);//accountsrev is sorted here
<?php
$accounts = '';
$i = 0;
while ($data = $getdata->fetch(PDO::FETCH_ASSOC)) {
$i++;
if($i == 1){
$accounts = $data['id'];
} else {
$accounts .= $data['id'].',';
}
}
$accountsrev = explode(',',$accounts); // explode it as make array
rsort($accountsrev); // then use rsort which sort array reverse
$accountsrev = implode(',',$accountsrev); // again implode it
echo $accountsrev;
?>
then output will be
6,5,4,3,2,1
or you can use array_reverse () function instead rsort
echo $accountsrev = implode(',',array_reverse(explode(',',$accounts)));
then output will be
6,5,4,3,2,1
Quick and easy:
$accounts = '1,2,3,4,5,6';
echo $accountsrev = implode(',',array_reverse(explode(',',$accounts)));
Related
I want the loop just to output once. Instead it outputs twice. Here is the code:
$results = mysql_query($query);
while ($c = mysql_fetch_array($results)){
$individualPostcode = explode(",", $c['postcode']);
foreach($individualPostcode as $val){
$val = trim($val); //Get rid of spaces
if($val === $postcode){
echo $c['url']."<br>";
}
}
}
}
Here is the output:
http://www.dyno.com/home-security/local-experts/greater-london/dyno-locks-and-alarms-enfield
http://www.dyno.com/home-security/local-experts/greater-london/dyno-locks--alarms-enfield
http://www.dyno.com/home-security/local-experts/greater-london/dyno-locks-and-alarms-enfield
http://www.dyno.com/home-security/local-experts/greater-london/dyno-locks--alarms-enfield
I've tried taken out the foreach loop but I need to go through that array checking against a user input.
Here is the initialisation of $postcode:
$userInput = $_POST["input"];
if(strlen($userInput) < 4)
echo "User Input : ".$userInput."<br>";
else //Below gets the first three chars of the users string
echo "User Input : $userInput<br>What is being used : ".mb_substr($userInput, 0, 3)."<br>";
$postcode = mb_substr($userInput, 0, 3);
You can always create an array of the URL's to stop them from duplicating by checking if the url has been put into the array:
$results = mysql_query($query);
$urlsArr = array();
while ($c = mysql_fetch_array($results)){
$individualPostcode = explode(",", $c['postcode']);
foreach($individualPostcode as $val){
$val = trim($val); //Get rid of spaces
if($val === $postcode){
if (!in_array($c['url'], $urlsArr)) echo $c['url']."<br>";
$urlsArr[] = $c['url'];
}
}
}
mysql_fetch_array returns both an associative and index array for each of your returned results. The foreach loop is going to loop over both and output twice. Try using mysql_fetch_assoc()
http://php.net/manual/en/function.mysql-fetch-array.php
Better still, try moving to the mysqli class. It's faster and mysql is depricated.
http://php.net/manual/en/intro.mysqli.php
Post Updated
I would like to create dynamic Array in PHP to provide the same output like static Array below, I have tried to do it with while statement but it doesn't work. Could you please provide me some tips?
I would like to use 2 values from MySQL and save them in to $to variable
so first send_to1 (user account) and then value1 (amount)
<?php
$con=mysqli_connect("localhost","test","test","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM users");
$to=Array(
while($row = mysqli_fetch_array($result))
{
$send_to1 => $value1,
$send_to2=> $value2
}
);
mysqli_close($con);
?>
It's as simple as just adding elements to the array:
//Setup blank array
$example = array();
//Create a loop, for example purposes.
foreach(range(0, 99) as $i){
//Create random variable that we'll add to our array
$randVar = mt_rand(1, 90000);
//$i will be our array key/index
$example[$i] = randVar;
}
//var_dump the array so you can see the structure / end result
var_dump($example);
You could also create it like so:
//Create random array key/index
$myRandKey = mt_rand(1, 90000);
//Create random variable value.
$myRandVar = mt_rand(1, 90000);
//Setup an array
$example = array(
$myRandKey => $myRandVar
);
//Another array key that we'll add to our array
$secondKey = 'test';
//Add it
$example[$secondKey] = 'This is just an example!';
//Dump out the array
var_dump($example);
array_push will also work (using mysql_fetch_assoc, like in your example):
$example = array();
while($row = mysql_fetch_assoc($result)){
array_push($example, $row);
}
var_dump($example);
In your particular example (since you added your code):
print_r($new_array[] = $row[]);
should be changed to:
print_r($new_array[] = $row);
In your code, I'd change it to:
$new_array = array();
while($row = mysqli_fetch_array($result)){
$new_array[] = $row;
}
Or, if you want to key your array by a unique column (Primary key, for example):
$new_array = array();
while($row = mysqli_fetch_array($result)){
$new_array[$row['id']] = $row;
}
Look, this is so easy, you just need to pay more attention to the answers you're getting here.
Here is the simplest way you can do it:
$to = array();
$to[] = array($send_to1 => $value1);
$to[] = array($send_to2 => $value2);
while ( $row = mysqli_fetch_array($result) ) {
$to[] = array($row['send_tox' => $row['valuex']);
}
You need to first understand how Arrays and Loops work in PHP, then try to make a dynamic array in a loop.
Actually you almost got it. It's lower A in 'array'
To initialize an empty array:
$to = array();
In your case (you already have some values), you can do:
$to = array(
$send_to1 => $value1,
$send_to2=> $value2
);
In either case, you can later add more elements doing
$to[$someOtherKey] = $someOtherValue;
A server sends me a $_POST request in the following format:
POST {
array1
{
info1,
info2,
info3
},
info4
}
So naturally, I could extract the info# very simply with $_POST['#info'].
But how do I get the the three info's in the array1?
I tried $_POST['array1']['info1'] to no avail.
Thanks!
a:2: {s:7:"payload";s:59:"{"amount":25,"adjusted_amount":17.0,"uid":"jiajia"}";s:9:"signature";s:40:"53764f33e087e418dbbc1c702499203243f759d4";}
is the serialized version of the POST
Use index notation:
$_POST['array1'][0]
$_POST['array1'][1]
$_POST['array1'][2]
If you need to iterate over a variable response:
for ($i = 0, $l = count($_POST['array1']); $i < $l; $i++) {
doStuff($_POST['array1'][$i]);
}
This more or less takes this shape in plain PHP:
$post = array();
$post['info'] = '#';
$post['array1'] = array('info1', 'info2', 'info3');
http://codepad.org/1QZVOaw4
So you can see it's really just an array in an array, with numeric indices.
Note, if it's an associative array, you need to use foreach():
foreach ($_POST['array1'] as $key => $val) {
doStuff($key, $val);
}
http://codepad.org/WW7U5qmN
try
$_POST['array1'][0]
$_POST['array1'][1]
$_POST['array1'][2]
You can simply use a foreach loop on the $_POST
foreach($_POST["array1"] as $info)
{
echo $info;
}
or you can access them by their index:
for($i = 0; $i<sizeof($_POST["array1"]); $i++)
{
echo $_POST["array1"][$i];
}
I have a function to use but I don't know the content of this function. The only thing I know is that the function returns an array of associative arrays and the keys for the arrays. The data that the function returns come from a database. Can you help in how to read the data from this array? I am confused with the arrays. For now I am doing this:
$array = myfunction($var);
if(!empty($array))
{
while($row = mysql_fetch_array($array))
{
print"$row[elem1]
$row[elem2]";
}
}
I take the error: Warning: mysql_fetch_array() expects parameter 1 to be resource, array given in... I know that something is missing, but I till now I can't fix it.
If the function is returning an array then why are you using it in mysql_fetch_array. It is useless. Instead use this
foreach($array as $key => $value){
echo $key;
echo '<br>';
echo $value;
}
This will print the whole array.
Or a short method is
echo '<pre>';
print_r($array);
echo '</pre>';
Something like -
$array = myfunction($var);
foreach($array as $key => $row) {
print"{$row['elem1']} {$row['elem2']}";
}
You have to pass Resource Identifier to mysql_fetch_array() function.
Something like:
$sql = mysql_query('SELECT * FROM `table`');
if(!empty($array)) {
while($row = mysql_fetch_array($array)) {
print"$row[elem1]
$row[elem2]";
}
}
The error is correct .. the issue is not associative arrays in php but you are not using a valid mysql resource
Please see http://php.net/manual/en/function.mysql-fetch-array.php for documentation
Examples
$mysqli = new mysqli("localhost","root","","test");
$result = $mysqli->query("SELECT * FROM test");
$row = array() ;
echo "<pre>" ;
if($result->num_rows > 0)
{
while($row = $result->fetch_array(MYSQLI_NUM))
{
print implode (",", $row) . PHP_EOL;
}
}
Or
$array = myfunction($var);
if(!empty($array))
{
foreach($array as $key => $row)
{
if(is_array($row))
{
print implode (",", $row) . PHP_EOL;
}
else
{
print $row . PHP_EOL ;
}
}
}
how take string from array define as new array,
how to code in php
$column = array("id","name","value");
let say found 3 row from mysql
want result to be like this
$id[0] = "1";
$id[1] = "6";
$id[2] = "10";
$name[0] = "a";
$name[1] = "b";
$name[2] = "c";
$value[0] = "bat";
$value[1] = "rat";
$value[2] = "cat";
I want to take string from $column array define as new array.
how to code it?
or if my question is stupid , my please to have suggestion.
thank you.
Answer I made on your previous question:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
$i = 0;
if ($num > 0) {
while ($row = mysql_fetch_assoc($result)) {
foreach($row as $column_name => $column_value) {
$temp_array[$column_name][$i] = $column_value;
}
$i++;
}
foreach ($temp_array as $name => $answer) {
$$name = $answer;
}
}
I can't see why you'd want to model your data like this, you're asking for a world of hurt in terms of debugging. There are "variable variables" you could use to define this, or build global variables dynamically using $GLOBALS:
$somevar = "hello"
$$somevar[0] = "first index"; // creates $hello[0]
$GLOBALS[$somevar][0] = "first index"; // creates $hello[0] in global scope
try
$array = array();
foreach ($results as $r){
foreach ($column as $col ){
$array[$col][] = $r[$col];
}
}
extract ($array);
or you can simply do this
$id = array();
$name = array();
$value = array();
foreach ( $results as $r ){
$id[] = $r['id']; // or $r[0];
$name[] = $r['name'];
$value[] = $r['value'];
}
Hope this is what you asked
This is pretty dangerous, as it may overwrite variables you consider safe in your code. What you're looking for is extract:
$result = array();
while ($row = mysql_fetch_array($result))
foreach ($column as $i => $c)
$result[$c][] = $row[$i];
extract($result);
So, if $result was array( 'a' => array(1,2), 'b' => array(3,4)), the last line defines variables $a = array(1,2) and $b = array(3,4).
You cannot use variable variables right on for this, and you shouldn't anyway. But this is how you could do it:
foreach (mysql_fetch_something() as $row) {
foreach ($row as $key=>$value) {
$results[$key][] = $value;
}
}
extract($results);
Ideally you would skip the extract, and use $results['id'][1] etc. But if you only extract() the nested array in subfunctions, then the local variable scope pollution is acceptable.
There is no need for arrays or using $_GLOBALS, i believe the best way to create variables named based on another variable value is using curly brackets:
$variable_name="value";
${$variable_name}="3";
echo $value;
//Outputs 3
If you are more specific on what is the array you receive i can give a more complete solution, although i must warn you that i have never had to use such method and it's probably a sign of a bad idea.
If you want to learn more about this, here is a useful link:
http://www.reddit.com/r/programming/comments/dst56/today_i_learned_about_php_variable_variables/