I want to assign values from an array to a simple variable, my code is as follows :
$codeval = $_POST['code']; //can be Apple or Banana or Cat or Dog
$systemrefcode = array("a" => "Apple", "b" => "Banana", "C" => "Cat", "D" => "Dog");
foreach($systemrefcode as $code => $value) {
if($codeval == $value){ //if Apple exists in array then assign code and use it further
$codes = $code;//Assign code to codes to use in next step
}
$selection = 'Your Selection is -'.$codes.'and its good.';
echo $selection;
When I check in console it shows no response. What am I doing wrong?
You can get the key of the wanted value with array_search():
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
So, for your code works, you can use like this:
$codeval = $_POST['code'];
$systemrefcode = array("a" => "Apple", "b" => "Banana", "C" => "Cat", "D" => "Dog");
$code = array_search($codeval, $systemrefcode);
$selection = 'Your Selection is - '.$code.' and its good.';
echo $selection;
OBS.:
array_search() will return false if value is not found;
array_search() is case sensitive, so if you have 'Apple' in the array and search for 'apple', it'll return false.
You can flip the $systemrefcode array so that the values become keys and vice versa.
$coderefsystem = array_flip($systemrefcode);
$codes = $coderefsystem($codeval);
$selection = 'Your Selection is -'.$codes.'and its good.';
echo $selection;
You could break out of the foreach when there is a match and echo the string afterwards.
$post = "1-Apple";
$codeval = explode('-', $post)[1];
$systemrefcode = array("a" => "Apple", "b" => "Banana", "C" => "Cat", "D" => "Dog");
$codes = "";
foreach ($systemrefcode as $code => $value) {
if ($codeval === $value) { //if Apple exists in array then assign code and use it further
$codes = $code;//Assign code to codes to use in next step
break;
}
}
if ($codes !== "") {
$selection = 'Your Selection is -' . $codes . ' and its good.';
echo $selection; // Your Selection is -a and its good.
} else {
echo "codes is empty";
}
Related
i have an json and i changed to array.
$asm1n = json_decode($asm_1);
print_r ($asm1n);
the result is
Array ( [0] => 2 [1] => 3 )
my problem is how to change it value based static value :
if it, 1 change to orange, 2 change apple, 3 change mango automatically
currently the value is like this in json:
["2","3"]
what i want to know how to make condition if the value like above it auto change to :
["apple","mango"]
i try use below code but i thing is wrong :
if ($asm1n == ["1","2","3"]){
$asm1n = "["orange","apple","mango"]";
}
this all data come from database, it might have value like this ["2","3"] , ["1","2","3"], ["1","3"].
how to change the number to the value like i said before? automatically or by if condition?
Try this:
$asm1n = ["2", "3"];
$data = array();
foreach( $asm1n as $key => $value ) {
if ( "1" === $value ) {
$data[] = "orange";
} elseif ( "2" === $value ) {
$data[] = "apple";
} elseif ( "3" === $value ) {
$data[] = "mango";
}
}
print_r($data);
You just need to ensure that you have the values and to use them to get your output
$myValues = [
1 => "orange",
2 => "apple",
3 => "mango"
];
$rawValues = json_decode($asm_1);
$asm1n = [];
foreach ($rawValues as $value) {
$asm1n[]=$myValues[$value];
}
print_r ($asm1n);
You could loop through your array and change it accordingly.
$fruits = [
1 => 'orange',
2 => 'apple',
3 => 'mango'
];
foreach($asm1n as &$value){
foreach($fruits as $key => $fruit){
if($value==$key){
$value = fruit;
}
}
}
I have two json strings in my database that contain data I'm trying to compare against one another to show in an activity log to see what a user has changed about an entry: old_properties and properties.
This is my current controller:
$properties = json_decode($log->properties, true);
$old_properties = json_decode($log->old_properties, true);
$changes = array_diff($properties, $old_properties);
This is my blade:
#foreach ($changes as $key => $value)
{{$key}}: {{$value}}<br>
#endforeach
So for example, if my data is:
old_properties: 'name' => 'Matthew', 'state' => 'Oregon'
properties: 'name' => 'Samuel', 'state' => 'Oregon'
all that I see from my $changes is: name: Samuel
What I am trying to display is: name: Matthew -> Samuel, or some other way to show what the old property was, and what it was changed to in the same line.
It looks like you could do something like:
#foreach ($changes as $key => $value)
{{$key}}: {{$old_properties[$key]}} -> {{$value}}<br>
#endforeach
Do Set calculation can solve this problem:
function printKeptAndUpdated ($setMapKeptAndUpdated, $setA, $setB) {
$changes = [];
foreach ($setMapKeptAndUpdated as $key => $value) {
$changes[] = $key . ": " . $setA[$key] . " -> " . $setB[$key];
}
echo("<pre>");
print_r($changes);
echo("</pre>");
}
$old_properties = [
"ape" => "black",
"cat" => "white",
"dog" => "black",
"fox" => "red",
];
$properties = [
"bear" => "brown",
"cat" => "white",
"dog" => "yellow",
"eagle" => "grey",
"fox" => "white",
"giraffe" => "yellow",
];
// Define 2 Set of array, setA is old set data, setB is new set data.
// Both setA and setB should only be one dimensional array
// which elements are always key => value pair only.
$setA = $old_properties;
$setB = $properties;
$setMap = [];
// Set map will do Set calculation in the future,
// and imply those 4 possibility: deleted, added, kept (updated or untouched),
// but only 3 of them are shown: deleted, added, kept.
// 4 possiblility after Set calculation.
$setMapDeleted = [];
$setMapAdded = [];
$setMapKeptAndUpdated = [];
$setMapKeptAndUntouched = [];
// Put $setA in $setMap first.
foreach($setA as $key => $value) {
$setMap[$key] = "a";
}
// Then put $setB in $setMap too.
foreach($setB as $key => $value) {
if (array_key_exists($key, $setMap)) {
$setMap[$key] = "ab";
} else {
$setMap[$key] = "b";
}
}
// So now the $setMap structure looks like this
// (just example, not as same as current data):
//$setMap = [
// "ape" => "b",
// "bear" => "ab",
// "cat" => "a",
// "dog" => "a",
// "eagle" => "b",
//];
// Where "a" = setA - setB, "b" = setB - setA, "ab" = setA ∩ setB (intersection)
// Now finish the Set calculation and also separate Set "kept" to set "updated" and Set "untouched".
foreach($setMap as $key => $value) {
if ($value === "a") {
$setMapDeleted[$key] = $setA[$key];
} elseif ($value === "b") {
$setMapAdded[$key] = $setB[$key];
} elseif ($value === "ab") {
if ($setB[$key] === $setA[$key]) {
$setMapKeptAndUntouched[$key] = $setB[$key];
} else {
$setMapKeptAndUpdated[$key] = $setB[$key];
}
}
}
printKeptAndUpdated($setMapKeptAndUpdated, $setA, $setB);
// Print the result you want.
I am trying get user value from multidimensional array as
$array = array();
$array["id"] = "1";
$array["name"] = "name1";
$array["country"] = "country1";
$array["id"] = "2";
$array["name"] = "name2";
$array["country"] = "country2";
$array["id"] = "3";
$array["name"] = "name3";
$array["country"] = "country3";
$array["id"] = "4";
$array["name"] = "name4";
$array["country"] = "country4";
foreach($array as $e){
print_r($e);
}
It return me 4name4country4 only
I need to fetch rows like
foreach($array as $e){
$id=$e['id'];
$name=$e['name'];
$country=$e['country'];
echo $id.'/'.$name.'/'.$country.'<br>';
}
but this gives me error as Illegal string offset 'id'
from what I understood about array this should return all values, Please see why this simple array is not working and suggest any way to do it
Currently you are overwriting the keys. Need to add the keys properly. You have to build the array like -
$array[0]["id"] = "1";
$array[0]["name"] = "name1";
$array[0]["country"] = "country1";
$array[1]["id"] = "2";
$array[1]["name"] = "name2";
$array[1]["country"] = "country2";
OR
$array = array(
0 => array('id' => 1, 'name' => 'name1', 'country' => 'country1'),
1 => array('id' => 2, 'name' => 'name2', 'country' => 'country2'),
);
Instead, do it like so you won't have to give array keys manually
$array = array();
$array[] = array("id" => 123, "name" => "Your name", "country" => "UK");
$array[] = array("id" => 1342, "name" => "Your name 2 ", "country" => "UK");
then in foreach do this
foreach($array as $key => $val){
echo $key. ": ".$val['id']. " " . $val['name'];
}
You have to create the multidimensional array like this, right now you're overwriting the array multiple times.
$arrays = [
[0]=>
["id"] => "1",
["name"] => "name1",
["country"] => "country1"
],
[1]=>[
...
]
];
foreach($arrays as $array){
$id=$array['id'];
$name=$array['name'];
$country=$array['country'];
echo $id.'/'.$name.'/'.'$country'.'<br>';
}
Let say I have an array as follows:
$my_array = array(
"fruit1" => "apple",
"fruit2" => "orange",
"notfruit" => "hamburger",
"fruit3" => "banana"
)
Is there a way I can choose to start with $my_array['notfruit'] in an foreach loop of PHP? I don't care the sequence except the first one.
Currently I can think of copying the whole piece of code once and change it specifically for $my_array['notfruit'], then unset it from the array to use foreach loop to go through the remaining. i.e.
echo $my_array['notfruit']."is not fruit. Who put that in the array?";
unset ($my_array['notfruit']);
foreach ($my_array as $values) {
echo $values." is fruit. I love fruit so I like ".$values;
}
It works but it sounds stupid, and can cause problem if the content in the foreach loop is long.
You can filter out any element with a key that doesn't begin with fruit pretty easily
$fruits = array_filter(
$my_array,
function ($key) {
return fnmatch('fruit*', $key);
},
ARRAY_FILTER_USE_KEY
);
var_dump($fruits);
though using array_filter() with the keys like this does require PHP >= 5.6
EDIT
For earlier versions of PHP, you can swap the keys/values before filtering; then flip them again afterwards
$fruits = array_flip(
array_filter(
array_flip($my_array),
function ($value) {
return fnmatch('fruit*', $value);
}
)
);
var_dump($fruits);
Short answer, no.
You can, however pull whatever functionality you intended to have in the foreach into a funcion, then call the funcion specifically for the notfruit value, then run the foreach.
function foo($val) {
// do stuff with $val
}
$my_array = array(
"fruit1" => "apple",
"fruit2" => "orange",
"notfruit" => "hamburger",
"fruit3" => "banana"
)
foo($my_array['nofriut']);
unset($my_array['nofruit']);
foreach($my_array as $val) {
foo($val);
}
EDIT
Or if your case is as simple as your updated question, simply check if the key is nofruit
foreach($my_array as $key => $val) {
if($key === "nofruit") {
echo "$val is not fruit. Who put that in the array?";
} else {
echo "$val is fruit. I love fruit so I like $val";
}
}
You can use addition in arrays, which is more performant than array_unshift.
So unset it, and then add it back:
unset($my_array['notfruit']);
$my_array = array('notfruit' => 'hamburger') + $my_array;
var_dump($my_array);
Or if you want to use a variable:
$keyToMove = 'notfruit';
$val = $my_array[$keyToMove];
unset($my_array[$keyToMove]);
$newArray = array($keyToMove => $val) + $my_array;
var_dump($newArray);
Obviously you can put this all in a loop, applying it to any that you need to move.
Try this..
<?php
$my_array = array(
"fruit1" => "apple",
"fruit2" => "orange",
"notfruit" => "hamburger",
"fruit3" => "banana"
);
$new_value['notfruit'] = $my_array['notfruit'];
unset($my_array['notfruit']);
$newarray=array_merge($new_value,$my_array);
print_r($newarray);
?>
Result:Array ( [notfruit] => hamburger [fruit1] => apple [fruit2] => orange [fruit3] => banana )
There is too many options.
1 . Using array_merge or array_replace (i think that it is the simplest way)
$my_array = array_merge(['notfruit' => null], $my_array);
// $my_array = array_replace(['notfruit' => null], $my_array);
foreach ($my_array as $key => $value) {
var_dump($key, $value);
}
2 . Using generators.
$my_array = array(
"fruit1" => "apple",
"fruit2" => "orange",
"notfruit" => "hamburger",
"fruit3" => "banana"
);
$generator = function($my_array){
yield 'notfruit'=>$my_array['notfruit'];
unset($my_array['notfruit']);
foreach($my_array as $key => $value)
yield $key => $value;
};
foreach ($generator($my_array) as $key=>$value){
var_dump($key, $value);
}
3 . Readding value
$no_fruit = $my_array['nofruit'];
unset($my_array['nofruit']);
$my_array['nofruit'] = $no_fruit;
$my_array = array_reverse($my_array, true);
foreach ($my_array as $key=>$value){
var_dump($key, $value);
}
4 . Using infinitive iterator
$infinate = new InfiniteIterator(new ArrayIterator($my_array));
$limit_iterator = new LimitIterator(
$infinate,
array_search('notfruit', array_keys($my_array)), // position of desired key
count($my_array));
foreach ($limit_iterator as $key => $value) {
var_dump($key, $value);
}
$no_fruit = $my_array['nofruit']; // grab the value
unset($my_array['nofruit']); // remove value from array
array_unshift($my_array, $no_fruit); // add value at the beginning
or
$no_fruit = $my_array['nofruit']; // grab the value
unset($my_array['nofruit']); // remove value from array
$my_array = array('nofruit' => $no_fruit ) + $my_array; // add value at the beginning
I'm trying to count the number of times a certain value appears in my multidimensional array based on a condition. Here's an example array;
$fruit = array (
"oranges" => array(
"name" => "Orange",
"color" => "orange",
"taste" => "sweet",
"healthy" => "yes"
),
"apples" => array(
"name" => "Apple",
"color" => "green",
"taste" => "sweet",
"healthy" => "yes"
),
"bananas" => array(
"name" => "Banana",
"color" => "yellow",
"taste" => "sweet",
"healthy" => "yes"
),
"grapes" => array(
"name" => "Grape",
"color" => "green",
"taste" => "sweet",
"healthy" => "yes"
)
);
If I want to DISPLAY all green coloured fruit, I can do the following (let me know if this is the best way of doing it);
for ($row = 0; $row < 3; $row++) {
if($fruit[$row]["color"]=="green") {
echo $fruit[$row]["name"] . '<br />';
}
}
This will output;
Apple
Grape
That's great and I can see their are 2 values there, but how can I actually get PHP to count the number of fruit where the colour is green and put it in a variable for me to use further down the script to work stuff out? E.g. I want to do something like;
if($number_of_green_fruit > 1) { echo "You have more than 1 piece of green fruit"; }
I've taken a look at count(); but I don't see any way to add a 'WHERE/conditional' clause (a la SQL).
Any help would be really appreciated.
PHP has no support for a SQL where sort of thing, especially not with an array of arrays. But you can do the counting your own while you iterate over the data:
$count = array();
foreach($fruit as $one)
{
#$count[$one['color']]++;
}
printf("You have %d green fruit(s).\n", $count['green']);
The alternative is to write yourself some little helper function:
/**
* array_column
*
* #param array $array rows - multidimensional
* #param int|string $key column
* #return array;
*/
function array_column($array, $key) {
$column = array();
foreach($array as $origKey => $value) {
if (isset($value[$key])) {
$column[$origKey] = $value[$key];
}
}
return $column;
}
You then can get all colors:
$colors = array_column($fruit, 'color');
And then count values:
$count = array_count_values($colors);
printf("You have %d green fruit(s).\n", $count['green']);
That kind of helper function often is useful for multidimensional arrays. It is also suggested as a new PHP function for PHP 5.5.
$number_of_green_fruit = 0;
for ($row = 0; $row < 3; $row++) {
if($fruit[$row]["color"]=="green") {
$number_of_green_fruit++;
echo $fruit[$row]["name"] . '<br />';
}
}
All you need is an extra counter:
for ($row = $number_of_green_fruit = 0; $row < 3; $row++) {
if($fruit[$row]["color"]=="green") {
echo $fruit[$row]["name"] . '<br />';
$number_of_green_fruit++;
}
}
if($number_of_green_fruit > 1) {
echo "You have more than 1 piece of green fruit";
}
With PHP 5.4+ you can have this short snippet to count specific values (don't even need to declare the $count variable previously)
array_walk_recursive($fruit, function ($value) use (&$count) {
$count += (int) ($value === 'green');
});
var_dump($count); // Outputs: int(2)