What does the => operator mean in the following code?
foreach ($user_list as $user => $pass)
The code is a comment at PHP.net.
The user does not specify the value of $user_list, $user or $pass.
I normally see that => means equal or greater than.
However, I am not sure about its purpose here because it is not assigned.
I read the code as
process a list of users in integers
such that the value of each user is equal or greater than password
The above does not make sense to me.
=> is the separator for associative arrays. In the context of that foreach loop, it assigns the key of the array to $user and the value to $pass.
Example:
$user_list = array(
'dave' => 'apassword',
'steve' => 'secr3t'
);
foreach ($user_list as $user => $pass) {
echo "{$user}'s pass is: {$pass}\n";
}
// Prints:
// "dave's pass is: apassword"
// "steve's pass is: secr3t"
Note that this can be used for numerically indexed arrays too.
Example:
$foo = array('car', 'truck', 'van', 'bike', 'rickshaw');
foreach ($foo as $i => $type) {
echo "{$i}: {$type}\n";
}
// prints:
// 0: car
// 1: truck
// 2: van
// 3: bike
// 4: rickshaw
It means assign the key to $user and the variable to $pass
When you assign an array, you do it like this
$array = array("key" => "value");
It uses the same symbol for processing arrays in foreach statements. The '=>' links the key and the value.
According to the PHP Manual, the '=>' created key/value pairs.
Also, Equal or Greater than is the opposite way: '>='. In PHP the greater or less than sign always goes first: '>=', '<='.
And just as a side note, excluding the second value does not work like you think it would. Instead of only giving you the key, It actually only gives you a value:
$array = array("test" => "foo");
foreach($array as $key => $value)
{
echo $key . " : " . $value; // Echoes "test : foo"
}
foreach($array as $value)
{
echo $value; // Echoes "foo"
}
Code like "a => b" means, for an associative array (some languages, like Perl, if I remember correctly, call those "hash"), that 'a' is a key, and 'b' a value.
You might want to take a look at the documentations of, at least:
foreach
arrays
Here, you are having an array, called $user_list, and you will iterate over it, getting, for each line, the key of the line in $user, and the corresponding value in $pass.
For instance, this code:
$user_list = array(
'user1' => 'password1',
'user2' => 'password2',
);
foreach ($user_list as $user => $pass)
{
var_dump("user = $user and password = $pass");
}
Will get you this output:
string 'user = user1 and password = password1' (length=37)
string 'user = user2 and password = password2' (length=37)
(I'm using var_dump to generate a nice output, that facilitates debuging; to get a normal output, you'd use echo)
"Equal or greater" is the other way arround: "greater or equals", which is written, in PHP, like this; ">="
The Same thing for most languages derived from C: C++, JAVA, PHP, ...
As a piece of advice: If you are just starting with PHP, you should definitely spend some time (maybe a couple of hours, maybe even half a day or even a whole day) going through some parts of the manual :-)
It'd help you much!
An array in PHP is a map of keys to values:
$array = array();
$array["yellow"] = 3;
$array["green"] = 4;
If you want to do something with each key-value-pair in your array, you can use the foreach control structure:
foreach ($array as $key => $value)
The $array variable is the array you will be using. The $key and $value variables will contain a key-value-pair in every iteration of the foreach loop. In this example, they will first contain "yellow" and 3, then "green" and 4.
You can use an alternative notation if you don't care about the keys:
foreach ($array as $value)
Arrays in PHP are associative arrays (otherwise known as dictionaries or hashes) by default. If you don't explicitly assign a key to a value, the interpreter will silently do that for you. So, the expression you've got up there iterates through $user_list, making the key available as $user and the value available as $pass as local variables in the body of the foreach.
$user_list is an array of data which when looped through can be split into it's name and value.
In this case it's name is $user and it's value is $pass.
Related
I would like to know how I can use the php extract function to extract the key from an array to change variables snake_case to camel_case.
Example:
array('id' => 1, 'user_name' => 'Paul');
To
$id = 1;
$userName = 'Paul';
I'm using laravel framework.
Thanks;)
foreach($array as $key => $value) {
$name = camel_case($key);
$$name = $value;
}
You can't with extract.
Quoting the PHP Manual (emphasis mine):
array: An associative array. This function treats keys as variable names and values as variable values. For each key/value pair it will create a variable in the current symbol table, subject to flags and prefix parameters.
There is no flag to change the case of the keys. It will use the array key as it appears in the array for the variable name. If you want camel case, you need to change the array key. There is no other way with extract.
You could do this in userland with this piece of code:
$data = array('id' => 1, 'user_name' => 'Paul');
foreach ($data as $k => $v) {
${lcfirst(str_replace('_', '', ucwords($k, '_')))} = $v;
}
echo $userName;
And apparently, Laravel has a helper function for that doing roughly the same under the hood.
But seriously… don't. That's very pointless to do. It's a complete waste of CPU to transform the key to camel case. Just use $user_name or $data['user_name'].
So I have a List of Variables
$TestData1="Hello";
$TestData2="";
$TestData3="0";
$TestData4="Yes";
$TestData5=" ";
$TestData6="No";
I want to make a function that will run all these variables through a filter. I want to make this a loop that checks all the variables in one shot. I had the idea of storing the variable names in an array. This is shown below.
$TestArray=array("TestData1", "TestData2", "TestData3", "TestData4","TestData5","TestData6");
So my main question is how would I take these names in the array and run a loop that checks to see if a certain condition is met. Example below.
foreach ($TestArray as $Data):
$VariableToTestConnditions="$".$Data;
endforeach;
I know that statement doesn't work, but it is all I could think of. The out come of this would be if the variable value =="Yes" then is would change the original variable's value to "N/A". So after it checks all the variables, it would change $TestData4 to "N/A".
instead of having an array of the names, it would make more sense to have an associative array (key value pairs):
$TestArray = array(
"TestData1" => "Hello",
"TestData2" => "",
"TestData3" => "0",
"TestData4" => "Yes",
"TestData5" => " ",
"TestData6" => "No"
);
now if you wanted to test a variable:
foreach($TestArray as $key => $value) {
if($VariableToTestConnditions == $value) {
//do something
}
}
if you wanted to change the value of a testdata:
$TestArray["TestData1"] = "Good Bye";
this way is much neater and simpler.
i used echo to demo the syntax, you can use what you like
$TestData1="Hello";
$TestData2="";
$TestData3="0";
$TestData4="Yes";
$TestData5=" ";
$TestData6="No";
$TestArray=array("TestData1", "TestData2", "TestData3", "TestData4","TestData5","TestData6");
foreach($TestArray as $a){
echo ${$a};
//or
echo $$a;
}
Use the two-dollar sign.
See PHP variable variables: http://php.net/manual/en/language.variables.variable.php
foreach ($TestArray as $Data):
$VariableToTestConnditions=$$Data;
endforeach;
I have a multi-dimensional array of databases, which was generated from my server:
// place db tables into array
$da_db = array(
'test' => array(
// test.users
'users' => array('fname','lname','info'),
// test.webref_rss_details
'webref_rss_details' => array('id','title','link','description','language','image_title','image_link','item_desc','image_width','image_height','image_url','man_Edit','webmaster','copyright','pubDate','lastBuild','category','generator','docs','cloud','ttl','rating','textInput','skipHours','skipDays'),
// test.webref_rss_items
'webref_rss_items' => array('id','title','description','link','guid','pubDate','author','category','comments','enclosure','source','chan_id')
),
'db_danaldo' => array(
//code here
),
'frontacc' => array(
//code here
)
[array][db][table][field]
As you can see, the database currently populated refers to an RSS project I am working on - one table for Channels, another for Items in that channel, at the moment that is another issue ('Users' table for now is not important)..
what I want to do is to return the array/sub-array names and convert each into variables for use as part of a string in an SQL Query, also need an alias for the tables I need to connect with:
(e.g. SELECT * FROM 'webref_rss_items' WHERE 'chan_id' = 'test.webref_rss_details.id')
where 'webref_rss_items' is a variable, 'chan_id' is a variable and 'test.webref_rss_details.id' are 3 variables in a concatenated string, although I've heard the concatenation in an SQL Query is not good practice, security-wise.. the strange thing is of all of those values, all I can retreive is the deepest level, 'id':
echo "{$da_db['test']['webref_rss_details'][0]}"
but get 'Array' returned or the last value of an array when I try to access the names!!
The reason for this is that the PHP file with the query will be within the 'public' part of the server and would like to have use variables with have no connotation to the original name(s), also it seems more convenient as the variables can be interchangable and I won't be using the same path all the time.
EDIT: My idea is to get key names from ['db'] to ['field']. The closest I have reached is to iterate keys and array_fill in a foreach loop, use range() inside another foreach, array_combine both then var_dump combined array like so:
foreach($da_db['test'] as $key1 => $val) { //put key-names into array1 to use as values
$a = array();
$a = array_fill(0, 1, $key1);
print($key1.'<br />');
}
foreach (range(0, 2) as $number) { //array for numbers to use as keys
$b = array();
$b = array_fill(0, 1, $number);
echo $number.'<br />';
}
$c = array_combine($b, $a); //combine both for new array
print_r($c.'<br />');
I could the use array_slice to get the name I want! (long winded?)
The problem is that the result of this only shows the last key => value; depending on command(print_r, print, echo), it shows:
[2] => webref_rss_items
OR
Array.
I hope that is enough info for now.
I've seen similar questions on here, but normally apply to one value, or one level of an array, but if you have seen this question before please advise and point me in right direction.
Your two top level arrays (db name and table name) are "named-key" arrays. The field level array (value of table name array) is an "integer key" array. PHP automatically adds numerical indexes for arrays that are defined with values only. For "named-key" arrays, you can only access their values by using the key name you defined.
For example:
$array1 = array('zero', 'one', 'two');
echo $array1[2]; // two
$array2 = array('zero' => 'this is zero', 'one' => 'this is one');
echo $array2['zero']; // this is zero
echo $array2[0]; // undefined
PHP provides a function called array_keys() that will return you an integer index array with all the key names. So you access your table array using an integer value, you can do this.
$da_db_test_keys = array_keys($da_db['test']);
echo $da_db_test_keys[1];
Maybe this will help you a little bit. I wasn't 100% on how you planned on accessing the values in your arrays, so if you have any more questions please try to clarify that part.
I'm developing a php app that uses a database class to query MySQL.
The class is here: http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql/*note there are multiple bad practices demonstrated in the tutorial -- it should not be used as a modern guide!
I made some tweaks on the class to fit my needs, but there is a problem (maybe a stupid one).
When using select() it returns a multidimensional array that has rows with 3 associative columns (id, firstname, lastname):
Array
(
[0] => Array
(
[id] => 1
[firstname] => Firstname one
[lastname] => Lastname one
)
[1] => Array
(
[id] => 2
[firstname] => Firstname two
[lastname] => Lastname two
)
[2] => Array
(
[id] => 3
[firstname] => Firstname three
[lastname] => Lastname three
)
)
Now I want this array to be used as a mysql result (mysql_fetch_assoc()).
I know that it may be used with foreach(), but this is with simple/flat arrays. I think that I have to redeclare a new foreach() within each foreach(), but I think this could slow down or cause some higher server load.
So how to apply foreach() with this multidimensional array the simplest way?
You can use foreach here just fine.
foreach ($rows as $row) {
echo $row['id'];
echo $row['firstname'];
echo $row['lastname'];
}
I think you are used to accessing the data with numerical indices (such as $row[0]), but this is not necessary. We can use associative arrays to get the data we're after.
You can use array_walk_recursive:
array_walk_recursive($array, function ($item, $key) {
echo "$key holds $item\n";
});
With arrays in php, the foreach loop is always a pretty solution.
In this case it could be for example:
foreach($my_array as $number => $number_array)
{
foreach($number_array as $data = > $user_data)
{
print "Array number: $number, contains $data with $user_data. <br>";
}
}
This would have been a comment under Brad's answer, but I don't have a high enough reputation.
Recently I found that I needed the key of the multidimensional array too, i.e., it wasn't just an index for the array, in the foreach loop.
In order to achieve that, you could use something very similar to the accepted answer, but instead split the key and value as follows
foreach ($mda as $mdaKey => $mdaData) {
echo $mdaKey . ": " . $mdaData["value"];
}
Hope that helps someone.
Holla/Hello,
I got it! You can easily get the file name,tmp_name,file_size etc.So I will show you how to get file name with a line of code.
for ($i = 0 ; $i < count($files['name']); $i++) {
echo $files['name'][$i].'<br/>';
}
It is tested on my PC.
To get detail out of each value in a multidimensional array is quite straightforward once you have your array in place. So this is the array:
$example_array = array(
array('1','John','Smith'),
array('2','Dave','Jones'),
array('3','Bob','Williams')
);
Then use a foreach loop and have the array ran through like this:
foreach ($example_array as $value) {
echo $value[0]; //this will echo 1 on first cycle, 2 on second etc....
echo $value[1]; //this will echo John on first cycle, Dave on second etc....
echo $value[2]; //this will echo Smith on first cycle, Jones on second etc....
}
You can echo whatever you like around it to, so to echo into a table:
echo "<table>"
foreach ($example_array as $value) {
echo "<tr><td>" . $value[0] . "</td>";
echo "<td>" . $value[1] . "</td>";
echo "<td>" . $value[2] . "</td></tr>";
}
echo "</table>";
Should give you a table like this:
|1|John|Smith |
|2|Dave|Jones |
|3|Bob |Williams|
Example with mysql_fetch_assoc():
while ($row = mysql_fetch_assoc($result))
{
/* ... your stuff ...*/
}
In your case with foreach, with the $result array you get from select():
foreach ($result as $row)
{
/* ... your stuff ...*/
}
It's much like the same, with proper iteration.
Ideally a multidimensional array is usually an array of arrays so i figured declare an empty array, then create key and value pairs from the db result in a separate array, finally push each array created on iteration into the outer array. you can return the outer array in case this is a separate function call. Hope that helps
$response = array();
foreach ($res as $result) {
$elements = array("firstname" => $result[0], "subject_name" => $result[1]);
array_push($response, $elements);
}
I know this is quite an old answer.
Here is a faster solution without using foreach:
Use array_column
print_r(array_column($array, 'firstname')); #returns the value associated with that key 'firstname'
Also you can check before executing the above operation
if(array_key_exists('firstname', $array)){
print_r(array_column($array, 'firstname'));
}
Wouldn't a normal foreach basically yield the same result as a mysql_fetch_assoc in your case?
when using foreach on that array, you would get an array containing those three keys: 'id','firstname' and 'lastname'.
That should be the same as mysql_fetch_assoc would give (in a loop) for each row.
foreach ($parsed as $key=> $poke)
{
$insert = mysql_query("insert into soal
(pertanyaan, a, b, c, d, e, jawaban)
values
('$poke[question]',
'$poke[options][A]',
'$poke[options][B]',
'$poke[options][C]',
'$poke[options][D]',
'$poke[options][E]',
'$poke[answer]')");
}
If you need to do string manipulation on array elements, e.g, then using callback function array_walk_recursive (or even array_walk) works well. Both come in handy when dynamically writing SQL statements.
In this usage, I have this array with each element needing an appended comma and newline.
$some_array = [];
data in $some_array
0: "Some string in an array"
1: "Another string in an array"
Per php.net
If callback needs to be working with the actual values of the array,
specify the first parameter of callback as a reference. Then, any
changes made to those elements will be made in the original array
itself.
array_walk_recursive($some_array, function (&$value, $key) {
$value .= ",\n";
});
Result:
"Some string in an array,\n"
"Another string in an array,\n"
Here's the same concept using array_walk to prepend the database table name to the field.
$fields = [];
data in $fields:
0: "FirstName"
1: "LastName"
$tbl = "Employees"
array_walk($fields, 'prefixOnArray', $tbl.".");
function prefixOnArray(&$value, $key, $prefix) {
$value = $prefix.$value;
}
Result:
"Employees.FirstName"
"Employees.LastName"
I would be curious to know if performance is at issue over foreach, but for an array with a handful of elements, IMHO, it's hardly worth considering.
A mysql result set object is immediately iterable within a foreach(). This means that it is not necessary to call any kind of fetch*() function/method to access the row data in php. You can simply pass the result set object as the input value of the foreach().
Also, from PHP7.1, "array destructuring" allows you to create individual values (if desirable) within the foreach() declaration.
Non-exhaustive list of examples that all produce the same output: (PHPize Sandbox)
foreach ($mysqli->query("SELECT id, firstname, lastname FROM your_table") as $row) {
vprintf('%d: %s %s', $row);
}
foreach ($mysqli->query("SELECT * FROM your_table") as ['id' => $id, 'firstname' => $firstName, 'lastname' => $lastName]) {
printf('%d: %s %s', $id, $firstName, $lastName);
}
*note that you do not need to list all columns while destructuring -- only what you intend to access
$result = $mysqli->query("SELECT * FROM your_table");
foreach ($result as $row) {
echo "$row['id']: $row['firstname'] $row['lastname']";
}
This is the set of result from my database
print_r($plan);
Array
(
[0] => Array
(
[id] => 2
[subscr_unit] => D
[subscr_period] =>
[subscr_fee] =>
)
[1] => Array
(
[id] => 3
[subscr_unit] => M,Y
[subscr_period] => 1,1
[subscr_fee] => 90,1000
)
[2] => Array
(
[id] => 32
[subscr_unit] => M,Y
[subscr_period] => 1,1
[subscr_fee] => 150,1500
)
)
How can I change the $plan[0] to $plan[value_of_id]
Thank You.
This won't do it in-place, but:
$new_plan = array();
foreach ($plan as $item)
{
$new_plan[$item['id']] = $item;
}
This may be a bit late but I've been looking for a solution to the same problem. But since all of the other answers involve loops and are too complicated imho, I've been trying some stuff myself.
The outcome
$items = array_combine(array_column($items, 'id'), $items);
It's as simple as that.
You could also use array_reduce which is generally used for, well, reducing an array. That said it can be used to achieve an array format like you want by simple returning the same items as in the input array but with the required keys.
// Note: Uses anonymous function syntax only available as of PHP 5.3.0
// Could use create_function() or callback to a named function
$plan = array_reduce($plan, function($reduced, $current) {
$reduced[$current['id']] = $current;
return $reduced;
});
Note however, if the paragraph above did not make it clear, this approach is overkill for your individual requirements as outlined in the question. It might prove useful however to readers looking to do a little more with the array than simply changing the keys.
Seeing the code you used to assemble $plan would be helpful, but I'm going assume it was something like this
while ($line = $RES->fetch_assoc()) {
$plan[] = $line;
}
You can simply assign an explicit value while pulling the data from your database, like this:
while ($line = $RES->fetch_assoc()) {
$plan[$line['id']] = $line;
}
This is assuming $RES is the result set from your database query.
In my opinion, there is no simpler or more expressive technique than array_column() with a null second parameter. The null parameter informs the function to retain all elements in each subarray, the new 1st level keys are derived from the column nominated in the third parameter of array_column().
Code: (Demo)
$plan = array_column($plan, null, 'id');
Note: this technique is also commonly used to ensure that all subarrays contain a unique value within the parent array. This occurs because arrays may not contain duplicate keys on the same level. Consequently, if a duplicate value occurs while using array_column(), then previous subarrays will be overwritten by each subsequent occurrence of the same value to be used as the new key.
Demonstration of "data loss" due to new key collision.
$plans = array();
foreach($plan as $item)
{
$plans[$item['id']] = $item;
}
$plans contains the associative array.
This is just a simple solution.
$newplan = array();
foreach($plan as $value) {
$id = $value["id"];
unset($value["id"]);
$newplan[$id] = $value;
}