How to use 3 dimensional array in PHP - php

I'm doing some image processing in php and normally I never use array in php before.
I have to keep the value of rgb value of hold image in 3 dimensional array.
For example, rgbArray[][][]
the first [] is represent th weight, the second[] use to keep height and the last one is use to keep either red,greed or blue. How can i create an array in php that can keep this set of value.
Thank you in advance.

I think you're looking for a two dimensional array:
$rgbArray[$index] = array('weight'=>$weight, 'height'=>$height, 'rgb'=>$rgb);
But here is a 3 dimensional array that could make sense for what you're asking.
$rgpArray[$index] = array('red'=>array('weight'=>$weight, 'height'=>$height),
'green'=>array('weight'=>$weight, 'height'=>$height),
'blue'=>array('weight'=>$weight, 'height'=>$height));

Your example is a little confuse rgbArray[1][1][red], it looks like you want this:
$rgbArray = array(1 => array(1 => array('red' => 'value')));
echo $rgbArray[1][1]['red']; // prints 'value'
I recommend, as PMV said, to do next:
$rgbArray = array('weight' => 1, 'height' => 1, 'rgb' => 'red' );
or
$rgbArray = array();
$rgbArray['weight'] = 1; // int value
$rgbArray['height'] = 1; // int value
$rgbArray['rgb'] = 'red'; // string value
If it's not what you want please be more specific in order to be helped.

If yours array
$rgbArray = array('red'=>array('weight'=>$weight, 'height'=>$height),
'green'=>array('weight'=>$weight, 'height'=>$height),
'blue'=>array('weight'=>$weight, 'height'=>$height));
Then you can assign the value to rgbArray like
$weight = $rgbArray['red']['weight']
$height = $rgbArray['red']['height']
If yours array
$rgbArray = array('red'=>array($weight, $height),
'green'=>array($weight, $height),
'blue'=>array($weight, $height));
Then you can assign the value to rgbArray like
$weight = $rgbArray['red'][0]
$height = $rgbArray['red'][1]

Define three-dimensional array
$threeDimArray = array(array(
array("reza", "daud", "ome"),
array("shuvam", "himel", "izaz"),
array("sayanta", "hasib", "toaha")));
Printing three-dimensional array
for ($i=0; $i < count($threeDimArray); $i++) {
for ($j=0; $j < count($threeDimArray[$i]); $j++) {
for ($k=0; $k < count($threeDimArray[$i][$j]); $k++) {
echo $threeDimArray[$i][$j][$k];
echo " ";
}
echo "<br>";
}
}

Related

How to return value of an array inside a loop and use it outside in PHP

I have a code like this:
Lets assume that this arrays has this values:
$arr1 = array();
$arr2 = array();
$result = array();
$arr1[] = array( 'grade' => [1,2,3,4] );
$arr2[] = array( 'grade' => [1,2,3,4] );
foreach($arr1 as $a1){
$set1 = $a1['grade'];
foreach($arr2 as $a2){
$set2 = $a2['grade'];
}
$result[] = array('show_result' => $set1+$set2);
}
foreach{$result as $res){
echo $res['show_result'];
}
The output of the array $res['show_result'] must be:
2, 4, 6, 8
But I get the wrong addition of this arrays. Help will be much appreciated.
As Joni said, your first error is on line 3: ' should be ;
Then, you're not filling arrays like you wanted : array( 'grade' => 1,2,3,4 ); creates an array with first key is 'grade' with value '1', then second key is '0' with value '2' etc...
Your last foreach loop has a syntax error similar to your first error.
See a working correction here
$arr1 = array();
$arr2 = array();
$result = array();
array_push($arr1, 1, 2, 3, 4); //fill array with 4 values (integers)
array_push($arr2, 1, 2, 3, 4); //fill array with 4 values (integers)
//so $arr1 & $arr2 are now a 4 elements arrays
$length = count($arr1); //size of array, here 4
for ($i = 0; $i < $length; $i++) { //loop over arrays
array_push($result, ($arr1[$i] + $arr2[$i])); //fill the results array with sum of the values from the same position
}
var_dump($result);
You have quite a few syntax errors in your code.
Although this solution works, the idea behind using the same counter, $i, to extract a value from both arrays is brittle. For example, you'll get an Undefined offset if the first array has 5 grades instead of 4. If you take a step back and explain your problem in the larger context, perhaps we can provide a better solution. I get the sneaking suspicion you're asking an XY Problem.
http://sandbox.onlinephpfunctions.com/code/bb4f492c183fcde1cf4edd50de7ceebf19fe343a
<?php
$gradeList1 = ['grade' => [1,2,3,4]];
$gradeList2 = ['grade' => [1,2,3,4]];
$result = [];
for ($i = 0; $i < count($gradeList1['grade']); $i++) {
$first = $gradeList1['grade'][$i];
$second = $gradeList2['grade'][$i];
$result['show_result'][] = (int)$first + (int)$second;
}
var_dump($result);

Get the name of the variable which has the second lowest/smallest value with PHP

I have 4 variables and each of those have an integer assigned to them. Could anybody please let me know how I can get the name of the variable which has the second smallest value?
Thanks.
Use compact to set the variables to one array, sort the array, then use array slice to get the second value.
Then optionally echo the key of the second value.
$a = 2;
$b = 7;
$c = 6;
$d = 1;
$arr = compact('a', 'b', 'c', 'd');
asort($arr);
$second = array_slice($arr,1,1);
Echo "variable name " . Key($second) ."\n";
Echo "value " . ${key($second)};
https://3v4l.org/SVdCq
Updated the code with how to access the original variable from the array
Unless you have a structured way of naming your variables eg prefix_x there is no real way.
Recommended way is using an array like this:
$array = array(
"a" => 3,
"b" => 2,
"c" => 1,
"d" => 6
);
// Sort the array descending but keep the keys.
// http://php.net/manual/en/function.asort.php.
asort($array);
// Fetch the keys and get the second item (index 1).
// This is the key you are looking for per your question.
$second_key = array_keys($array)[1];
// Dumping the result to show it's the second lowest value.
var_dump($array[$second_key]); // int(2).
To be more in line with your question you can create your array like this.
$array = array();
$array['variable_one'] = $variable_one;
$array['some_random_var'] = $some_random_var;
$array['foo'] = $foo;
$array['bar']= $bar;
// Same code as above here.
Instead of using 4 variables for 4 integer values, you can use an array to store these values. Sort the array and print the second index of the array i.e. 1.
<?php
$x = array(2,3,1,6);
$i = 0, $j = 0, $temp = 0;
for($i = 0; $i < 4; $i++){
for($j=0; $j < 4 - $i; j++){
if($x[$j] > $x[$j+1]){
$temp = $x[$j];
$x[$j] = $x[$j+1];
$x[$j+1] = $temp;
}
}
}
for($j = 0; $j < 4; $j++){
echo $x[$j];
}
echo $x[1];
?>
First you need to have all Variables in an Array. You can do this this way:
$array = array(
'a' => 3,
'b' => 6,
'c' => 2,
'd' => 1
);
or this way:
$array['a'] = 3;
$array['b'] = 6;
// etc
Then you need to sort the Items with natsort() to receive a natural Sorting.
natsort($array);
Then you flip the Array-Keys with the Values (In Case you want the Value, skip this Line)
$array = array_flip($array);
After this you jump to the next Item in the Array (Position 1) by using next();
echo next($array);
Makes in Total a pretty short Script:
$array = array(
'a' => 3,
'b' => 6,
'c' => 2,
'd' => 1
);
natsort($array);
$array = array_flip($array);
echo next($array);

PHP find max between variables

I'm trying to find out wich variable is bigger (those are all integers):
<?php
$ectoA=3;
$ectoB=5;
$mesoA=0;
$mesoB=4;
$endoA=11;
$endoB=11;
echo max($ectoA,$ectoB,$mesoA,$mesoB,$endoA,$endoB);
I tried with max but it gives the value and not the $varName.
I want to get the name of the variable and if there are two that are equal I need both.
Thanks for the help.
As suggested i tried this and worked but still got to know if I have two MAX values I need to do something else...
$confronto = [
'ectoA' => $ectoA,
'ectoB' => $ectoB,
'endoA' => $endoA,
'endoB' => $endoB,
'mesoA' => $mesoA,
'mesoB' => $mesoB,
];
$result= array_keys($confronto,max($confronto));
$neurotipo = $result[0];
echo $neurotipo;
I want endoA and endoB to be identified...
You can define an array instead, or compact your variables into an array:
//$array = array('ectoA'=>3,'ectoB'=>5,'mesoA'=>0,'mesoB'=>4,'endoA'=>11,'endoB'=>11);
$array = compact('ectoA','ectoB','mesoA','mesoB','endoA','endoB');
$result = array_keys($array, max($array));
Then compute the max() of that array and use array_keys() to search for the max number and return the keys.
print_r($result);
Yields:
Array
(
[0] => endoA
[1] => endoB
)
I would definitely recommend using an array. Then you can do something like this:
$my_array = array(3, 5, 0, 4, 11, 11);
$maxIndex = 0;
for($i = 1; $i < count($my_array); $i++) {
if($my_array[$i] > $my_array[$maxIndex])
$maxIndex = $i;
}
Another option with array keys would be:
$my_array = array("ectoA" => 3, "ectoB" => 5, "mesoA" => 0, "mesoB" => 4, "endoA" => 11, "endoB" => 11);
$maxIndex = "ectoA";
while($c = current($my_array)) {
$key = key($my_array);
if($my_array[$key] > $my_array[$maxIndex])
$maxIndex = $key;
next($my_array);
}
Note: Code not tested, but should be the gist of what needs to be done
use the array like this
<?php
$value= array (
"ectoA" =>3,
"ectoB"=>5,
"mesoA"=>0,
"mesoB"=>4,
"endoA"=>11,
"endoB"=>11);
$result= array_keys($value,max($values))
print_r($result);
?>
As per the documentation, Since the two values are equal, the order they are provided determines the result $endoA is the biggest here.
But I am not sure your intention is to find the biggest value or which variable is the highest
Your code seems to be a working one.
But it would print for you the value of the maximum number, not the name of the variable.
To have the name of the variable at the end you should add some additional code like:
$max = (max($ectoA,$ectoB,$mesoA,$mesoB,$endoA,$endoB);
if($max == $ectoA) echo "ectoA";
if($max == $ectoB) echo "ectoB";
// ... same goes for other variables
But working with an array would be the most proper solution.

Creating, Accessing and understanding multidimensional arrays in php

I have implemented the following small example:
$nodeList;
for($i = 0; $i < 10;$i++) {
$nodeList[$i] = $i;
for($j = 0; $j < 3;$j++) {
$nodeList[$i][$j] = $j;
}
}
foreach($nodeList[0] as $nodeEl) {
print "NodeEl: ".$nodeEl." | ";
}
print nl2br("\n\r");
$testList = array
(
array(1,2,3),
array(4,5,6),
array(7,8,9),
array(10,11,12),
);
foreach($testList[0] as $testEl) {
print "TestEl: ".$testEl." | ";
}
Where the output for $nodeList is null (var_dump / print_r too) and the output for $testList is TestEl: 1 | TestEl: 2 | TestEl: 3, as expected.
In my understanding those two solutions should create roughly the same output - but instead there is no output for the first one at all. Because the second dimension of the array is not even created.
Reading up on http://php.net/manual/de/language.types.array.php creates the strong feeling that the [] operator is only for dereferencing / accessing of the array, but then again the docs provide a sample where they assign a value to a certain key the same way I do $arr["x"] = 42.
What is the difference between these two ways of array access?
How can I achieve filling a n-dimensional array in a way similar to the way I try to fill $nodeList?
You should make sure to have error reporting turned on, because warnings are generated for your code:
E_WARNING : type 2 -- Cannot use a scalar value as an array -- at line 7
This concerns the following statement:
$nodeList[$i] = $i;
If you want to create a 2D array, there is no meaning in assigning a number on the first level. Instead you want $nodeList[$i] to be an array. PHP does that implicitely (creating the array) when you access it with brackets [...], so you can just leave out the offending statement, and do:
for($i = 0; $i < 10;$i++) {
for($j = 0; $j < 3;$j++) {
$nodeList[$i][$j] = $j;
}
}
You can even leave out the $j in the last bracket pair, which means PHP will just add to the array using the next available numerical index:
for($i = 0; $i < 10;$i++) {
for($j = 0; $j < 3;$j++) {
$nodeList[$i][] = $j;
}
}
Adding a value at every level
If you really need to store $i at the first level of the 2D array, then consider using a more complex structure where each element is an associative array with two keys: one for the value and another for the nested array:
for($i = 0; $i < 10; $i++) {
$nodeList[$i] = array(
"value" => $i,
"children" => array()
);
for($j = 0; $j < 3;$j++) {
$nodeList[$i]["children"][] = array(
"value" => "$i.$j" // just example of value, could be just $j
);
}
}
$nodeList will be like this then:
array (
array (
'value' => 0,
'children' => array (
array ('value' => '0.0'),
array ('value' => '0.1'),
array ('value' => '0.2'),
),
),
array (
'value' => 1,
'children' => array (
array ('value' => '1.0'),
array ('value' => '1.1'),
array ('value' => '1.2'),
),
),
//...etc
);
You should write
<?php
$nodeList;
for($i = 0; $i < 10;$i++) {
for($j = 0; $j < 3;$j++) {
$nodeList[$i][$j] = $j;
}
}
foreach($nodeList[0] as $nodeEl) {
print "NodeEl: ".$nodeEl." | ";
}
You need to declare $nodeList as array like
$nodeList=array();
and for 2D array
$nodeList= array(array());

Replace non-specified array values with 0

I want to replace all array values with 0 except work and home.
Input:
$array = ['work', 'homework', 'home', 'sky', 'door']
My coding attempt:
$a = str_replace("work", "0", $array);
Expected output:
['work', 0, 'home', 0, 0]
Also my input data is coming from a user submission and the amount of array elements may be very large.
A bit more elegant and shorter solution.
$aArray = array('work','home','sky','door');
foreach($aArray as &$sValue)
{
if ( $sValue!='work' && $sValue!='home' ) $sValue=0;
}
The & operator is a pointer to the particular original string in the array. (instead of a copy of that string)
You can that way assign a new value to the string in the array. The only thing you may not do is anything that may disturb the order in the array, like unset() or key manipulation.
The resulting array of the example above will be
$aArray = array('work','home', 0, 0)
A loop will perform a series of actions many times. So, for each element in your array, you would check if it is equal to the one you want to change and if it is, change it. Also be sure to put quote marks around your strings
//Setup the array of string
$asting = array('work','home','sky','door')
/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting);$i++){
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work' || $asting[$i] == 'home')
$asting[$i] = 0;
}
Here is some suggested reading:
http://www.php.net/manual/en/language.types.array.php
http://www.php.net/manual/en/language.control-structures.php
But if you are struggling on stuff such as looping, you may want to read some introductory programming material. Which should help you really understand what's going on.
A bit other and much quicker way, but true, need a loop:
//Setup the array of string
$asting = array('bar', 'market', 'work', 'home', 'sky', 'door');
//Setup the array of replacings
$replace = array('home', 'work');
//Loop them through str_replace() replacing with 0 or any other value...
foreach ($replace as $val) $asting = str_replace($val, 0, $asting);
//See what results brings:
print_r ($asting);
Will output:
Array
(
[0] => bar
[1] => market
[2] => 0
[3] => 0
[4] => sky
[5] => door
)
An alternative using array_map:
$original = array('work','home','sky','door');
$mapped = array_map(function($i){
$exclude = array('work','home');
return in_array($i, $exclude) ? 0 : $i;
}, $original);
you may try array_walk function:
function zeros(&$value)
{
if ($value != 'home' && $value != 'work'){$value = 0;}
}
$asting = array('work','home','sky','door','march');
array_walk($asting, 'zeros');
print_r($asting);
You can also give array as a parameter 1 and 2 on str_replace...
Just a small point to the for loop. Many dont realize the second comparing task is done every new iteration. So if it was a case of big array or calculation you could optimize loop a bit by doing:
for ($i = 0, $c = count($asting); $i < $c; $i++) {...}
You may also want to see http://php.net/manual/en/function.array-replace.php for original problem unless the code really is final :)
Try This
$your_array = array('work','home','sky','door');
$rep = array('home', 'work');
foreach($rep as $key=>$val){
$key = array_search($val, $your_array);
$your_array[$key] = 0;
}
print_r($your_array);
There are a few techniques on this page that make zero iterated function calls -- which is good performance-wise. For best maintainability, I recommend separating your list of targeted string as a lookup array. By modifying the original array values by reference, you can swiftly replace whole strings and null coalesce non-targeted values to 0.
Code: (Demo)
$array = ['work', 'homework', 'home', 'sky', 'door'];
$keep = ['work', 'home'];
$lookup = array_combine($keep, $keep);
foreach ($array as &$v) {
$v = $lookup[$v] ?? 0;
}
var_export($array);
Output:
array (
0 => 'work',
1 => 0,
2 => 'home',
3 => 0,
4 => 0,
)
You can very easily, cleanly extend your list of targeted strings by merely extending $keep.
If you don't want a classic loop, you can use the same technique without modifying the original array. (Demo)
var_export(
array_map(fn($v) => $lookup[$v] ?? 0, $array)
);
this my final code
//Setup the array of string
$asting = array('work','home','sky','door','march');
/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting); $i++) {
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work') {
$asting[$i] = 20;
} elseif($asting[$i] == 'home'){
$asting[$i] = 30;
}else{
$asting[$i] = 0;
}
echo $asting[$i]."<br><br>";
$total += $asting[$i];
}
echo $total;

Categories