i am trying to create array like in the example i wrote above:
$arr=array('roi sabah'=>500,yossi levi=>300,dana=>700);
but i want to create it dynamic with foreach.
how can i do it ?
thanks.
You can access an array with foreach (and optionally create another one while going through the array's values). But if you only have data like a name and a number from your example, not stored in an array, you can't use foreach.
Another way to create the array you mentioned:
$arr = array();
$arr['roi sabah'] = 500;
$arr['yossi levi'] = 300;
// etc
And to access these values:
foreach ($arr as $key => $value) {
// $key is e.g. "roi sabah", and its value "500"
}
Related
While I map all the links on a page that is contained in an array, I want to check if each of the links is inserted in this array and, if not, insert it.
I'm trying to use the code bellow without success because "foreach $arr" doesn't pass by in the new values.
include_once('simple_html_dom/simple_html_dom.php');
$arr = array('http://www.domain.com');
foreach ($arr as $key => &$item) {
$html = file_get_html($item);
// Find category links
foreach($html->find('a[href^=http://www.domain.com/dep/]') as $element) {
if (!in_array($element->href, $arr))
$arr[] = $element->href;
}
}
print_r($arr);
Important: I need to search and add value in the original array, not in the copy (foreach).
First of all
In foreach ($arr as $key => &$item) { every $item is a STRING. (As a warning told you). So you shouldn't use $item[] here.
Next pitfall: if you want to add new items to your $arr array symtax should be
$arr[] = $some_var;
But you shouldn't do this because every time you add items to $arr, this array increases and you iterate not over two elements array, but for example 3-elements or 4 elements. Do you expect this?
You should find new values, put them in some other array and then merge both arrays.
Or use #splash58 solution. It's even simplier.
First off this question in in relation to this question. My issue is that a friend of mine has upwards of around 300 or so arrays that she needs to insert into the database. I get the database part as you notice in the question I linked I have that part down. My question however arises on just how exactly I am supposed to get all the arrays and bring them together so that I could could do a foreach on the arrays and check if a value is an array, if it is then use the arrays name as the table in the INSERT query.
This is my updated code :
$colors['Colors_All'] = array("Black","Charcoal"); // Add unique indexes
$colors['Colors_Bright_All'] = array("Silver","White"); // Add unique indexes
$AllArrays = get_defined_vars(); // Get all defined vars
$Arrays = array(); // Set a default array
foreach ($AllArrays as $varName => $value) { // Run through all the variables set in the get_defined_vars
if(is_array($value) && $varName == 'colors') { // If it is an array and if the array is colors[] then
$Arrays = array_merge($Arrays, $value); // Merge those arrays into the new array
}
}
This will now give me access to all the data.
Here you go:
$colors['Colors_All'] = array("Black","Charcoal","Light_Gray","Silver","White","Gold","Bronze","Copper","Platinum","Navy","Royal_Blue","Dodger_Blue","Deep_Sky_Blue","Turquoise","Tiffany_Blue");
$colors['Colors_Bright_All'] = array("Silver","White","Gold","Royal_Blue","Dodger_Blue","Deep_Sky_Blue","Deep_Green","Forest_Green","Bright_Green","Violet");
$colors['Colors_Light_All'] = array("Light_Gray","Silver","White","Gold","Dodger_Blue","Deep_Sky_Blue","Light_Blue","Bright_Green","LightGreen","Light_Green");
// This will store the merged results of each array
$colorVars = array();
// Loop through all of the defined variables
foreach ($colors as $colorKey => $value) {
// Add the results of this array to the main $colorVars array
$colorVars = array_merge($colorVars, $value);
}
foreach ($topicarray as $key=>$value){
$files = mysql_query("mysqlquery");
while($file = mysql_fetch_array($files)){ extract($file);
$topicarray[$value] = array( array($id=>$title)
);
}
}
The first foreach loop is providing me with an array of unique values which forms a 1-dimensional array.
The while loop is intended to store another array of values inside the 1-dimensional array.
When the while loop returns to the beginning, it is overwriting it. So I only ever get the last returned set of values in the array.
My array ends up being a two dimensional array with only one value in each of the inner arrays.
Feels like I'm missing something very basic here - like a function or syntax which prevents the array from overwriting itself but instead, adds to the array.
Any ideas?
Step 1. Replace $topicarray[$value] with $topicarray[$value][]
Step 2. ???
Step 3. Profit
Make $topicarray[$value] an array of rows, instead of one row. Also, don't use extract here.
foreach ($topicarray as $key => $value) {
$rows = array();
$files = mysql_query("mysqlquery");
while($file = mysql_fetch_array($files)) {
$rows[] = array($file['id'] => $file['title']);
}
$topicarray[$value] = $rows;
}
Also, you should switch to PDO or MySQLi.
So I don't think I'm making full use of the foreach loop. Here is how I understand foreach.
It goes like foreach(arrayyouwanttoloopthrough as onevalueofthatarray)
No counter or incrementing required, it automatically pulls an array, value by value each loop, and for that loop it calls the value whatever is after the "as".
Stops once it's done with the array.
Should basically replace "for", as long as dealing with an array.
So something I try to do a lot with foreach is modify the array values in the looping array. But in the end I keep finding I have to use a for loop for that type of thing.
So lets say that I have an array (thing1, thing2, thing3, thing4) and I wanted to change it....lets say to all "BLAH", with a number at the end, I'd do
$counter = 0;
foreach($array as $changeval){
$counter++;
$changeval = "BLAH".$counter;
}
I would think that would change it because $changeval should be whatever value it's at for the array, right? But it doesn't. The only way I could find to do that in a] foreach is to set a counter (like above), and use the array with the index of counter. But to do that I'd have to set the counter outside the loop, and it's not even always reliable. For that I'd think it would be better to use a for loop instead of foreach.
So why would you use foreach over for? I think I'm missing something here because foreach has GOT to be able to change values...
Thanks
OH HEY One more thing. Are variables set in loops (like i, or key) accessible outside the loop? If I have 2 foreach loops like
foreach(thing as value)
would I have to make the second one
foreach(thing2 as value2) ]
or else it would have some problems?
You can use a reference variable instead:
foreach ($array as &$value)
{
$value = "foo";
}
Now the array is full of foo (note the & before $value).
Normally, the loop variable simply contains a copy of the corresponding array element, but the & (ampersand) tells PHP to make it a reference to the actual array element, rather than just a copy; hence you can modify it.
However, as #Tadeck says below, you should be careful in this case to destroy the reference after the loop has finished, since $value will still point to the final element in the array (so it's possible to accidentally modify it). Do this with unset:
unset($value);
The other option would be to use the $key => $value syntax:
foreach ($array as $key => $value)
{
$array[$key] = "foo";
}
To answer your second question: yes, they are subsequently accessible outside the loop, which is why it's good practice to use unset when using reference loop variables as in my first example. However, there's no need to use new variable names in subsequent loops, since the old ones will just be overwritten (with no unwanted consequences).
You want to pass by reference:
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value)
{
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
The extended foreach syntax is like this:
foreach ($array as $key => $value) {
}
Using the $key, you can index the original array:
foreach ($array as $key => $value) {
$array[$key] = "BLAH";
}
Incrementing from 0 to ...
foreach($array as $changeval){
if (!isset($counter)) { $counter = 0; }
$counter++;
$changeval = "BLAH".$counter;
}
Using the index/key of the ARRAY
foreach($array as $key => $changeval){
$changeval = "BLAH".$key;
}
You can use the key when looping with foreach:
foreach ($array as $key => $value)
{
$array[$key] = "foo";
}
But note that using a reference like Will suggested will be faster for such a case - but anyway, the $key => $value-syntax is quite useful sometimes.
How can I dynamically create variable names based on an array? What I mean is I want to loop through this array with a foreach and create a new variable $elem1, $other, etc. Is this possible?
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
//create a new variable called $elem1 (or $other or $elemother, etc.)
//and assign it some default value 1
}
foreach ($myarray as $name) {
$$name = 1;
}
This will create the variables, but they're only visible within the foreach loop. Thanks to Jan Hančič for pointing that out.
goreSplatter's method works and you should use that if you really need it, but here's an alternative just for the kicks:
extract(array_flip($myarray));
This will create variables that initially will store an integer value, corresponding to the key in the original array. Because of this you can do something wacky like this:
echo $myarray[$other]; // outputs 'other'
echo $myarray[$lastelement]; // outputs 'lastelement'
Wildly useful.
Something like this should do the trick
$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
foreach ($myarray as $arr){
$myVars[$arr] = 1;
}
Extract ( $myVars );
What we do here is create a new array with the same key names and a value of 1, then we use the extract() function that "converts" array elements into "regular" variables (key becomes the name of the variable, the value becomes the value).
Use array_keys($array)
i.e.
$myVars = Array ();
$myarray = array('elem1', 'other', 'elemother', 'lastelement');
$namesOfKeys = array_keys($myVars );
foreach ($namesOfKeys as $singleKeyName) {
$myarray[$singleKeyName] = 1;
}
http://www.php.net/manual/en/function.array-keys.php