PHP removing elements from array in a foreach loop - php

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

Related

foreach $key variable clarification

I have this code
if (isset($_POST['submit2']))
{
foreach ($_POST['check_list'] as $key) {
$input = implode(",", $key);
}
} /*end is isset $_POST['submit2'] */
echo $input;
it produces the error " implode(): Invalid arguments passed " when I change the implode arguments to implode(",", $_POST['check_list']) it works as intended.
Can someone clarify why? As far as I understand the $key variable should be the same as the $_POST['submit2'] isn't that what the as in the foreach does?
Sorry if it's a silly question, I'm self taught and sometimes details like that are hard to find online.
You seem confused at several levels, so let me clarify some of them:
You said 'As far as I understand the $key variable should be the same as the $_POST['submit2'] isn't that what the as in the foreach does?'. The answers are NO and NO:
The $key variable outside the foreach loop will contain the last element of the array that's stored in $_POST['check_list'], $_POST['submit2'] seems to be only used to check if is set and nothing else in your piece of code. What foreach does is to traverse any iterator variable (an array in your case) and set the current item in a variable ($key) in your case. So after the loop, $key will contain the last element of that array. For more information refer to the docs: [http://php.net/manual/en/control-structures.foreach.php]
implode expects the second parameter to be an array, it seems you're not providing an array, but any other type. Is the last item of $_POST['check_list'] actually an array?
If you're trying to 'glue' together all items of $_POST['check_list'], you don't need to iterate, you just use implode on that one: $input = implode(",", $_POST['check_list']);. Otherwise, i'm not sure what are you trying to do.
Maybe if you explain what are you trying to do, we can help better.
Foreach already iterates trough your values. You can either get the value and echo it from there or you can add it to another array input if thats what you need:
if (isset($_POST['submit2']))
{
foreach ($_POST['check_list'] as $key => $value) {
$input[] = 'Value #'. $key .' is ' . $value;
}
}
echo implode(",", $input);
You are saying that $_POST['check_list'] is an array if implode() works on it, so no need to loop to get individual items. To implode() the values:
echo implode(',', $_POST['check_list']);
To implode() the keys:
echo implode(',', array_keys($_POST['check_list']));
foreach() iterates over an array to expose each item and get the individual values and optionally keys one at a time:
foreach($_POST['check_list'] as $key => $val) {
echo "$key = $value<br />";
}
implode function needs array as second argument. You are passing string value as second argument. That's why it's not working.

Multidimensional array - how to get specific values from array

I have converted Excel data into Php array using toArray()..
actually my result is
My question how to get value from this Multidimensional array? and also how to i get header and value from array in separately?
you can access value, by following the path of the array. so in your case :
$yourArrayName['Worksheet'][0][0], will return SNo
Get one value:
print_r($your_array['Worksheet'][0]);
Get values with loop:
foreach ($your_array as $key => $value)
{
echo $key; // 'Worksheet'
print_r $value;
}
If you are trying to extract all the values of specific key then you should use for or foreach or while loop...
its something like
<?php
$array = YOUR ARRAY;
$c=count($array);
for ( $i=0; $i < $c; $i++)
{
echo $array[$i]['StudentName'];
}
?>
else if you want to get a specific value manually You can easily traverse to your value as
$array = YOUR ARRAY
echo $ara['Worksheet'][0]['StudentName']

Pushing key/value pairs to an array, loses key out of forloop

I get my data from the database, but want to add 2 keys to them. So I add them in a for loop. If I dump (simple function that prints the array with pre tags) the single result in the for loop, it's correct, when I dump the 2dimensional array outside of it, it doesn't have the keys anymore..
For some reason it doesn't push it to the 2dimensional array?
$results is a 2dimensional array btw.
//add amount and subtotal to the array's elements
foreach ($results as $result) {
$result['amount'] = $sessionShoppingCart[$result['artikelnummer']][1];
$result['subtotal'] = $result['amount'] * $result['Verkoopprijs'];
$this->dump($result);
}
$this->dump($results);
To change an array within the foreach you can do two things.
Reference the array value with &:
foreach ($results as &$result) {
Or use the key and modify the array:
foreach ($results as $key => $result) {
$results[$key]['amount'] = $sessionShoppingCart[$result['artikelnummer']][1];
$results[$key]['subtotal'] = $result['amount'] * $result['Verkoopprijs'];
}

Add a value to array inside loop

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.

Strange Printing on arrays

I'm testing the performances/hitches for References over copies of an array. I have the following code:
function ScoreWords($Value){
$WordList = array(
"Amazing" => 1,
"Value" => 300,
"Elements" => 30,
"Another" => 0
);
if (array_key_exists($Value,$WordList)){
return $WordList[$Value];
}
}
$array = ["Value","Another",1,2,3,4];
echo implode(',', $array), "<br>";
foreach ($array as &$value) {
ScoreWords($value);
}
echo implode(',', $array), "<br>";
foreach ($array as $value) {
ScoreWords($value);
}
echo implode(',', $array), "<br>";
But it seems, the code pasted above works semi-fine. Output is:
Value,Another,1,2,3,4
Value,Another,1,2,3,4
Value,Another,1,2,3,3
I found this by mistake as imploding was not actually necessary, but this sparks the question. Why is there a duplicated value for the final print rather than the correct value of 4? regardless of what the content of the array is. It seems to duplicate the second from last element as the last element?
What is happening is that after your 1st foreach, $value is a reference to the last element in the array. As that loop progressed it was a reference to each element, until finally stopping at the last one.
So, when the 2nd foreach runs, $value is still a reference. As that loop runs, it updates $value, which in turn, updates the last element in the array.
When it gets to the last element, it was set to 3 from the previous loop iteration. So, that's why it's set to 3 at the end.
To fix this, unset($value); after your first foreach.
The thing here is that you have to unset the value when you pass it by reference:
foreach ($array as &$value) {
ScoreWords($value);
}
unset($value); // break the reference with the last element
Warning Reference of a $value and the last array element remain even
after the foreach loop. It is recommended to destroy it by unset().
Foreach reference

Categories