Add a value to array inside loop - php

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.

Related

clone array and add a subarray

i have the following problem. i have a large array structure which i assign values from a sql statement:
$data[$user][$month]['id'] = $data->id;
$data[$user][$month]['company'] = $data->company;
...
...
and around 30 other values.
i need to clone this array ($data) and add a subarray like:
$data[$user][$month][$newsubarray]['id'] = $data->id;
$data[$user][$month][$newsubarray]['company'] = $data->company;
...
...
i need to clone it because the original array is used by many templates to display data.
is there a way to clone the array and add the subarray without assign all the values to the cloned array? this blows up my code and is very newbi, but works.
You can use array_map, check the live demo
if you want to pass parameter to array_map(), use this
array_map(function($v) use($para1, $para2, ...){...}, $array);
Here is the code,
<?php
$array =array('user'=> array('month'=>array('id' =>2, 'company' => 3)));
print_r($array);
print_r(array_map(function($v){
$arr = $v['month'];
$v['month'] = [];
$v['month']['newsubarray'] = $arr;
return $v;}
, $array));
You can iterate through the array with nested foreach loops.
It would look similar to this:
foreach ($data as $user=>$arr2) {
foreach ($arr2 as $month=>$arr3) {
foreach ($arr3 as $key=>$value) {
$data[$user][$month][$newsubarray][$key] = $value;
}
}
}
Your last level of array, you can create object, for holding data with implementing ArrayAccess. Then simply by reference, assign object in desire places. This way, you can hold 1 object and use it multi places, but if you change in one - this change in all.
Then you addictionaly, can implements __clone method to clone object correctly.

PHP foreach insert array

I have an array of arrays, and I am trying to foreach loop through and insert new item into the sub arrays.
take a look below
$newarray = array(
array("id"=>1,"quantity"=>2),
array("id"=>1,"quantity"=>2),
array("id"=>1,"quantity"=>2),
);
foreach($newarray as $item){
$item["total"] = 9;
}
echo "<br>";
print_r($newarray);
The result just give me the original array without the new "total". Why ?
Because $item is not a reference of $newarray[$loop_index]:
foreach($newarray as $loop_index => $item){
$newarray[$loop_index]["total"] = 9;
}
The foreach() statement gives $item as an array: Not as the real value (consuming array). That meaning it can be read but not changed unless you then overwrite the consuming array.
You could use the for() and loop through like this: see demo.
Note: This goes all the way back to scopes, you should look into that.

PHP removing elements from array in a foreach loop

I'm trying to unset() some elements from an array but when using a foreach loop to go through 1 array to delete these elements from another array it does not seems to be working.
if (isset($this->request->post['merge'])) {
$merge_orders = $this->request->post['merge'];
}
$selected_order = min($merge_orders); // Fetch the max value order_id
unset($merge_orders[$selected_order]); // Take it out of the array.
$orders_list = explode(',', $this->request->post['order_id_list']);
$removeKeys = $merge_orders;
foreach($removeKeys as $key) {
unset($orders_list[$key]);
echo $key;
}
echo print_r($orders_list);
The first unset works fine but the second does not, the array is set and properly formatted but it still does not seem to remove the elements from the $orders_list array.
If you only use one parameter on a foreach loop you are delivered the value of the occurance and not the key for the occurance.
Try this so that you are getting a key from the foreach loop and not a value
foreach($removeKeys as $key => $val) {
unset($orders_list[$key]);
echo $key;
}

Using foreach effectively in PHP

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 create array with foreach in php?

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"
}

Categories