I am trying to use foreach statment to run through a function that preg_replaces using regular expression. Can someone help, because my method doesn't work..
$reg_sent is an array
function reg_sent($i){
$reg_sent = "/[^A-Za-z0-9.,\n\r ]/";
return preg_replace($reg_sent, '', $i);
}
foreach($reg_sent as $key=>$value){
$value = reg_sent($value);
}
Check array_map.
$reg_sent = array_map("reg_sent", $reg_sent);
This will call reg_sent on every cell of the array, and return a new array with values modified. You can replace the foreach block you stated, with the above.
You're not getting any affect because the foreach loop needs to access the elements by reference:
foreach($reg_sent as $key => &$value)
{
$value = reg_sent($value);
}
Note that I added the & in the loop before $value. Otherwise, foreach operates on a copy of the value, and when that is modified within the loop, you will never see that value outside of the loop.
You need to pass your variable by reference:
foreach($reg_sent as $key=>&$value){
Otherwise you are operating on a local copy that only keeps its value in the loop.
function reg_sent($i){
$reg_sent = "/[^A-Za-z0-9.,\n\r ]/";
return preg_replace($reg_sent, '', $i);
}
foreach($reg_sent as $key => &$value){
$value = reg_sent($value);
}
unset($value);
var_dump($reg_sent);
Related
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.
I have an array, I need to loop through and change it's value:
foreach ($input['qualification'] as &$_v) {
$_v = ucwords($_v);
}
But this only works for the first item in the array. When I remove the ampersand it loops through the entire array, but obviously the changes are not made.
If you're trying to apply a function to all of the values in an array I would recommend using array_map() instead.
Applies the callback to the elements of the given arrays
$qualifications = array_map('ucwords', $input['qualification']);
Demo
$input['qualification'] = array('high school', 'inter school', 'bachelor of scinece', 'master of science');
foreach ($input['qualification'] as &$_v) {
$_v = ucwords($_v);
}
echo "<pre>";print_r($input['qualification']);
Here is how to do it more slowly, with explicit reference to the index, in case your actual programming task requires the value of the index.
https://eval.in/436395
$input = array('juggling','french','math');
foreach ($input as $i=>$v) {
$input[$i] = ucwords($v);
}
I've done a multistep form in PHP storing the data in a multidimensional array (I've created an array inside $_SESSION array and named it $_SESSION['inserimento'])
then i have $_SESSION['inserimento']['name'],$_SESSION['inserimento']['city']...
I would like to apply the strtolower() function to all the values before adding them to mysql
I've tried this code but it doesn't work
foreach ($_SESSION['inserimento'] as $k=>$v){
$v=strtolower($v);
}
I think I'm misunderstanding how to make a loop on multidimensional array.
Use array_map() to apply a function to all elements in an array:
$_SESSION['inserimento'] = array_map('strtolower', $_SESSION['inserimento']);
Or a regular foreach loop (inside the loop $v is a copy, so you need to affect to the original array):
foreach ($_SESSION['inserimento'] as $k => $v) {
$_SESSION['inserimento'][$k] = strtolower($v);
}
Or a foreach loop with reference ($v is no longer a copy, it is a reference to the original element):
foreach ($_SESSION['inserimento'] as &$v) {
$v = strtolower($v);
}
unset($v); // remember to unset, or $v will still be a reference to the last element after the loop
Use:
foreach ($_SESSION['inserimento'] as $k => $v) {
$_SESSION['inserimento'][$k] = strtolower($v);
}
This is happening because $v is a copy of the value inside the iteration, not a reference to the variable that contains the value.
You need to have a variable defined outside of the foreach loop.
$lowerValue = '';
foreach ($_SESSION['inserimento'] as $k => $v) {
$lowerValue = strtolower($v);
}
Try using array_walk
array_walk($_SESSION['inserimento'], function(&$value, $key) {
$value = strtolower($value);
});
The & before $value indicates that the variable is passed by reference.
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.
I want to loop through an array with foreach to check if a value exists. If the value does exist, I want to delete the element which contains it.
I have the following code:
foreach($display_related_tags as $tag_name) {
if($tag_name == $found_tag['name']) {
// Delete element
}
}
I don't know how to delete the element once the value is found. How do I delete it?
I have to use foreach for this problem. There are probably alternatives to foreach, and you are welcome to share them.
If you also get the key, you can delete that item like this:
foreach ($display_related_tags as $key => $tag_name) {
if($tag_name == $found_tag['name']) {
unset($display_related_tags[$key]);
}
}
A better solution is to use the array_filter function:
$display_related_tags =
array_filter($display_related_tags, function($e) use($found_tag){
return $e != $found_tag['name'];
});
As the php documentation reads:
As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior.
In PHP 7, foreach does not use the internal array pointer.
foreach($display_related_tags as $key => $tag_name)
{
if($tag_name == $found_tag['name'])
unset($display_related_tags[$key];
}
Instead of doing foreach() loop on the array, it would be faster to use array_search() to find the proper key. On small arrays, I would go with foreach for better readibility, but for bigger arrays, or often executed code, this should be a bit more optimal:
$result=array_search($unwantedValue,$array,true);
if($result !== false) {
unset($array[$result]);
}
The strict comparsion operator !== is needed, because array_search() can return 0 as the index of the $unwantedValue.
Also, the above example will remove just the first value $unwantedValue, if the $unwantedValue can occur more then once in the $array, You should use array_keys(), to find all of them:
$result=array_keys($array,$unwantedValue,true)
foreach($result as $key) {
unset($array[$key]);
}
Check http://php.net/manual/en/function.array-search.php for more information.
if you have scenario in which you have to remove more then one values from the foreach array in this case you have to pass value by reference in for each:
I try to explain this scenario:
foreach ($manSkuQty as $man_sku => &$man_qty) {
foreach ($manufacturerSkus as $key1 => $val1) {
// some processing here and unset first loops entries
// here dont include again for next iterations
if(some condition)
unset($manSkuQty[$key1]);
}
}
}
in second loop you want to unset first loops entries dont come again in the iteration for performance purpose or else then unset from memory as well because in memory they present and will come in iterations.
There are already answers which are giving light on how to unset. Rather than repeating code in all your classes make function like below and use it in code whenever required. In business logic, sometimes you don't want to expose some properties. Please see below one liner call to remove
public static function removeKeysFromAssociativeArray($associativeArray, $keysToUnset)
{
if (empty($associativeArray) || empty($keysToUnset))
return array();
foreach ($associativeArray as $key => $arr) {
if (!is_array($arr)) {
continue;
}
foreach ($keysToUnset as $keyToUnset) {
if (array_key_exists($keyToUnset, $arr)) {
unset($arr[$keyToUnset]);
}
}
$associativeArray[$key] = $arr;
}
return $associativeArray;
}
Call like:
removeKeysFromAssociativeArray($arrValues, $keysToRemove);