I'm having a problem looping through my array to get just one value each time. I want to gray only 1 value because I'm calling that value in jquery. I'm new and sorry if this is too basic but I've been trying for days, pulling my hair out!
$designslist = array('design1','design2','design3','design4');
$current_index = 0;
$current_id = current($designslist);
$next = $designslist[$current_index + 1];
foreach( $designslist as $value )
{
if( $value !== $next )continue;
$nexts = $next;
echo $nexts;
$current_index++;
}
Inside my html
next
calling the id with jquery
$('#design1').on('click',function() {
$('#web1').removeClass().addClass('big1');
});
foreach( $designslist as $value )
needs to be
foreach( $designslist as $i => $value )
$i is the array index
You can try array search
$tag = array_search($value, $designslist);
$nexts = $$designslist[$tag];
Ok, you seem to be mixing for with foreach using these "current_id" and "next" variables.
You can use this kind of foreach statement:
foreach ($designList as $key => $value) {
echo "The key of $value is $key";
}
As you want to return only unique values, you should use the "array_unique" function. Try this:
foreach (array_unique($designList) as $key => $value) {
echo "The key of $value is $key";
}
I know it's not related to the question, but, as you said you're new to this, there are some PHP tips you should follow.
You're mixing snake_case with camelCase in your variables. I recommend using camelCase, but it's up to you.
Related
I have a foreach loop for an array
foreach ($somethings as $key2 => $something)
{
$value = 0;
if ($something['ElementID'] == $value)
{
unset($available);
}
$total += $something['Cost'];
$singleprice = $available['Cost'];
}
I need to be able to return $total and $singleprice - Total adding up all the values within the key, $singleprice returning only 1 instead of all added up
The only way I've managed to return this value is by creating another foreach loop within this foreach loop like so:
foreach ($somethings as $key2 => $something)
{
$value = 0;
if ($something['ElementID'] == $value)
{
unset($available);
}
foreach($somethings as $key3 => $singlesomething)
{
$singleprice = $singlesomething['Cost'];
}
$total += $something['Cost'];
}
Why will the above first method return nothing? I then use this variable which now has the data in a Div Data- (data-single-cost="'.$singleprice.'" ) which is then used to POST a form
$singleprice = $_POST['single-cost'];
Yet it returns 0 even with the second method successfully getting the value
any ideas what I'm doing wrong?
I guess its because somehow program goes into the if and you have unset available in it, so singleprice gots nothing.
Maybe you should get a Xdebug and try some step debug to see what happend.
I need to get every key-value-pair from an array in PHP. The structure is different and not plannable, for example it is possible that a key contains an additional array and so on (multidimensional array?). The function I would like to call has the task to replace a specific string from the value. The problem is that the function foreach, each, ... only use the main keys and values.
Is there existing a function that has the foreach-function with every key/value?
There is not a built in function that works as you expect but you can adapt it using the RecursiveIteratorIterator, walking recursively the multidimensional array, and with the flag RecursiveIteratorIterator::SELF_FIRST, you would get all the elements of the same level first, before going deeper, not missing any pair.
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $key => $item) {
// LOGIC
}
The usual approach to this kind of task is using a recursive funcion.
Let's go step by step:
First you need the foreach control statement...
http://php.net/manual/en/control-structures.foreach.php
..that let you parse the associative array without knowing keys' names beforehand.
Then is_array and is_string (and eventually is_object, is_integer...) let you check the type of each value so you can act properly.
http://php.net/manual/en/function.is-array.php
http://php.net/manual/en/function.is-string.php
If you find the string to be operated then you do the replace task
If you find an array the function recalls itself passing the array just parsed.
This way the original array will be parsed down to the deepest level without missing and key-value pair.
Example:
function findAndReplaceStringInArray( $theArray )
{
foreach ( $theArray as $key => $value)
{
if( is_string( $theArray[ $key ] )
{
// the value is a string
// do your job...
// Example:
// Replace 'John' with 'Mike' if the `key` is 'name'
if( $key == 'name' && $theArray[ $key ] == "John" )
{
$theArray[ $key ] = "Mike";
}
}
else if( is_array( $theArray[ $key ] )
{
// treat the value as a nested array
$nestedArray = $theArray[ $key ];
findAndReplaceStringInArray( $nestedArray );
}
}
}
You can create a recursive function to treat it.
function sweep_array(array $array)
{
foreach($array as $key => $value){
if(is_array($value))
{
sweep_array($value);
}
else
{
echo $key . " => " . $value . "<br>";
}
}
}
I'm trying to foreach through an array of objects inside an array. I'm not receiving errors, but it seems not to be storing the new value I'm trying to establish. I've found many answers on here closely related to this question, but I'm not understanding, and I'm hoping someone can make this clearer.
Essentially, this converts kg to lbs.
$kg_conv = 2.20462262;
$weights = array($data['progress']->weight, $data['progress']->squats,
$data['progress']->bench, $data['progress']->deadlift);
foreach ($weights as $value) {
$value = $value * $kg_conv;
}
The values in the array come out unchanged. From what I've read, I should be using $data['progress'] and iterating through that, but I'm not understanding how to refer to only some of the elements inside instead of all of them. I also tried cutting out some redundancy by storing the objects in $progress instead of $data['progress'] but still not success.
UPDATE: The following has not worked
1
foreach ($weights as &$value) {
$value = $value * $kg_conv;
}
2
foreach ($weights as $key => &$value) {
$value = $value * $kg_conv;
}
3
foreach ($weights as $key => $value) {
$weights[$key] = $value * $kg_conv;
}
it does not work because you do not modify data array, you only modify copy made from this array, which is another array in memory
Solution: (will work for object's fields too)
$kg_conv = 2.20462262;
$weights = ['weight', 'squats','bench', 'deadlift'];
foreach ($data['progress'] as $key=>&$value) {
if ( in_array($key,$weights)
$value = $value * $kg_conv;
}
$value contains only a copy of the array element.
You can pass the object by reference like this:
foreach ($weights as &$value) {
$value = $value * $kg_conv;
}
Note the & before $value.
See References Explained in the php documentation or What's the difference between passing by reference vs. passing by value? here on stackoverflow.
Edit 2:
But note that this will only change the values in the $weights array, not your object stored in $data['progress'], as it's value has been copied into $weights. To achieve this, you can reference the object properties when constructing the data array in the following way (this step was commented out in my testcase code) :
$weights = array(&$data['progress']->weight, &$data['progress']->squats,
&$data['progress']->bench, &$data['progress']->deadlift);
Note the & operator again.
But probably the solution of maxpower is cleaner for your requirement.
Edit:
After your comment I created the following test case which works fine:
<?php
class foo {
public $test = 5;
public $test2 = 10;
}
$obj = new foo();
$obj2 = new foo();
$obj2->test = 3;
$data = array('progress' => $obj, 'p2' => $obj2);
// this copies the values into the new array
$weights = array($data['progress']->test, $data['progress']->test2);
// this makes a reference to the values, the original object will be modified
// $weights = array(&$data['progress']->test, &$data['progress']->test2);
var_dump($weights);
$kg_conv = 2.20462262;
foreach ($weights as &$value) {
$value = $value * $kg_conv;
}
var_dump($weights);
The result is:
array(2) {
[0]=>
int(5)
[1]=>
int(10)
}
array(2) {
[0]=>
float(11.0231131)
[1]=>
&float(22.0462262)
}
The PHP foreach manual describes this topic in great detail. To summarise why you are not seeing the results you expect, here is a short explanation.
Imagine you have an array $arr = ['one', 'two', 'three']. When you execute a foreach loop on this array, PHP will internally create a copy of your array:
foreach ($arr as $key => $value) {
$value = 'something'; // You are modifying the copy, not the original!
}
To modify the original array, you have two options.
Use the $key variable to access the element at given key in the original array:
$arr[$key] = 'something'; // Will change the original array
Tell PHP to use a reference to the original element in $value:
foreach ($arr as $key => &$value) {
$value = 'something'; // $value is reference, it WILL change items in $arr
}
Both approaches are valid; however, the second is more memory-efficient because PHP does not have to copy your array when you loop through it - it simply references the original.
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference. In your example code should look like this:
foreach ($weights as &$value) {
$value = $value * $kg_conv;
}
But referencing $value is only possible if the iterated array can be referenced (i.e. if it is a variable).
You can also use indexes to acces array value directly. This code works pretty fine too:
foreach ($weights as $key => $value) {
$weights[$key] = $value * $kg_conv;
}
More here: http://php.net/manual/en/control-structures.foreach.php
I have the following scenario:
$starterArray = array ('192.168.3.41:8013'=>0,'192.168.3.41:8023'=>0,'192.168.3.41:8033'=>0);
In the requirement I have another array which counts some events of the application, this array uses the same keys as my first array, but values can change), so at the end I could have something like:
$processArray = array ('192.168.3.41:8013'=>3,'192.168.3.41:8023'=>5,'192.168.3.41:8033'=>7);
I want to update the values of my starter array with the values of the process array, for instance, at the end, I should have:
$starterArray = array ('192.168.3.41:8013'=>3,'192.168.3.41:8023'=>5,'192.168.3.41:8033'=>7);
I know this can be achieved by using $starterArray = $processArray;
Then in some moments, I would need to sum some units to the values of my array, for example +1 or +2:
It should be something like the following?
foreach ($starterArray as $key => $value) {
$starterArray[$value] = $starterArray[$value]+1;
}
Then, for my process array, I need to set the values to 0
foreach ($processArray as $key => $value) {
$processArray[$value] = 0;
}
This is what I tried but it is not working, if somebody could help me I will really appreaciate it. Thanks in advance.
PD: I know these are strange requirements, but that's what I am asked to do...
You are almost there:-
foreach ($processArray as $key => $value) {
$starterArray[$key] = $value +1;
}
and then:-
foreach ($processArray as $key => $value) {
$processArray[$key] = 0;
}
However, you could do this all in one loop:-
foreach ($processArray as $key => $value) {
$starterArray[$key] = $value +1;
$processArray[$key] = 0;
}
You need to put $key in brackets, not $value.
Or, you can do:
foreach ($starterArray as $key => &$value) {
$value++; /* put here whatever formula you want */
}
foreach ($starterArray as $key => $value) {
$starterArray[$key] = $value+1;
// or $starterArray[$key] = 0;
}
Please i want to loop through my table and compare values with an array in a php included file. If there is a match, return the array key of the matched item and replace it with the value of the table. I need help in returning the array keys from the include file and comparing it with the table values.
$myarray = array(
"12aaa"=>"hammer",
"22bbb"=>"pinchbar",
"33ccr"=>"wood" );
in my loop in a seperate file
include 'myarray.inc.php';
while($row = $db->fetchAssoc()){
foreach($row as $key => $val)
if $val has a match in myarray.inc.php
{
$val = str_replace($val,my_array_key);
}
}
So in essence, if my db table has hammer and wood, $val will produce 12aaa and 3ccr in the loop. Any help? Thanks a lot
You are looking for array_search which will return the key associated with a given value, if it exists.
$result = array_search( $val, $myarray );
if ($result !== false) {
$val = $result;
}
your array should look like
$myarray = array(
"hammer"=>"11aaa",
"pinchbar"=>"22bbb",
"wood"=>"33ccr" );
and code
if (isset($myarray[$key])){
//do stuff
}
I think you need the function in_array($val, $myarray);
If you don't want or can't change $myarray structure like #genesis proposed, you can make use of array_flip
include 'myarray.inc.php';
$myarray = array_flip($myarray);
while($row = $db->fetchAssoc()) {
foreach($row as $key => $val) {
if (isset($myarray[$val])) {
// Maybe you should use other variable instead of $val to avoid confusion
$val = $myarray[$val];
// Rest of your code
}
}
}