Array (
[category] => abc
[post_tag] => test
[nav_menu] => Home
[link_category] => Link 1
[post_format] => format
)
print conditional value from a loop in php
How can i check if a key is present in this loop
foreach($array as $ar)
{
if($ar->category == 'abc')
{
echo 'found';
}
}
I'm not quite sure what you're trying to find but if it's specific key/value pair it should look like this:
$array = Array (
'category' => 'abc',
'post_tag' => 'test',
'nav_menu' => 'Home',
'link_category' => 'Link 1',
'post_format' => 'format'
);
foreach($array as $key => $value) {
if ($key === 'category' && $value === 'abc') echo 'found', PHP_EOL;
}
Here you just have an associated array that doesn't have any nested arrays.
So if you want to do what you want on this array, you should do something like this:
if (isset($array['category']) && $array['category'] === 'abc') {
echo 'Found!';
}
Using null coalescing operator can make it easier:
if ($array['category'] ?? null === 'abc') {
echo 'Found!';
}
Your question isn't very clear. Do you want to check if a key on an array exists or check if the value exists inside the foreach?
I will try to answer both.
Given that we have this array:
$array = [
'category' => 'abc'
'post_tag' => 'test'
'nav_menu' => 'Home'
'link_category' => 'Link 1'
'post_format' => 'format'
];
If you want to check if a key exists in an array and print the keys value:
if(array_key_exists('category', $array){
echo $array['category']; // prints abc
}
more info about array_key_exists here: array_key_exists
If you want to check if a value exists in the array:
foreach($array as $ar){
if($ar === 'abc'){
echo $ar; // prints abc
}
}
In case you want to check for both of the above:
if(array_key_exists('category', $array) && $array['category'] === 'abc'){
echo $array['category']; // prints abc
}
I hope this helps you figure things out.
Related
I'm new.
I have a situation where I need to loop through an array, determine if a $key in that array has a value of 1, then set a variable with the $value from different $key in the same array.
Here's what I mean.
I retrieve a JSON array from an API that looks, in part, like this:
(
[6] => Array
(
[element] => 191
[position] => 7
[multiplier] => 2
[is_captain] => 1
[is_vice_captain] =>
)
[7] => Array
(
[element] => 171
[position] => 8
[multiplier] => 1
[is_captain] =>
[is_vice_captain] =>
)
What I want to do is loop through the array, determine whether the key [is_captain] has a value (1), and set a variable using the value from a different $key, specifically [element].
For example, in the code above at [6], I want to create a variable with the value of [element] => 191 (191) if the value of [is_captain] is 1.
Here's where I left things:
for($i = 0; $i < count($players['picks']); $i++){
foreach ($fpl_team_picks['picks'][$keys[$i]] as $key => $value){
if (isset($key['is_captain'])){
$variable = $value['element'];
}
}
}
It doesn't work. I've tried the isset function and a series of array functions (array_column and others), and I'm stumped.
$arr = array(
6 => array(
'element' => 191,
'position' => 7,
'multiplier' => 2,
'is_captain' => 1,
'is_vice_captain' => null
),
7 => array(
'element' => 171,
'position' => 8,
'multiplier' => 1,
'is_captain' => null,
'is_vice_captain' => null
)
);
Set foreach loop on the array, set the values, loop through values, find the key value, $index === 'is_captain' and make sure it is set to 1 -> $data === '1'. If this is true define your variable.
foreach($arr as $value){
foreach($value as $index => $data){
if($index === 'is_captain' && $data === 1){
$element = $value['element'];
echo $element; // $element now holds the value where key = `element` if 'is_captain' is equal to `1`
}
}
}
In your code, change the $key['is_captain'] to $key === 'is_captain' then look for its value if it is a match with in that same conditional.
If the key is equal to target key is_captain and that keys value is equal to 1 get the value of the key set as element and assign it to your variable:
if ($key === 'is_captain' && $val === 1)){
$variable = $value['element'];
}
I was set in the right direction, so thanks immensely to the contributor for the help.
My original question didn't make clear that I was working with a nested array. My array snippet didn't show that. I've learned a lesson about completeness. (I'm new here).
Once I wrote the code block to handle the nested array and modified the conditional slightly, I was successful. Here's the final code which works:
$x = 0;
$captainsArr = array($fpl_team_picks['picks']);
foreach($captainsArr[$x++] as $value) {
if (is_array($value)){
foreach ($value as $index => $data) {
if ($index === 'is_captain' && $data == 1){
$captain = $value['element'];
}
}
}
}
I have an array with the following setup:
array(
array(
'product_id' => 733
),
array(
'product_name' => Example
)
)
I want to check that 733 exists in my array which I need to use array_search (going by googling) as in_array doesn't work on m-d arrays.
My code is:
$key = array_search( '733', array_column( $items, 'product_id' ) );
If I var_dump the $items array I can see the product_id
I want to check the specific ID exists in the array and then perform other code.
So basically you want to check that given product-id exist in your multidimensional array or not?
You can do it like below:-
<?php
$items = array(
array(
'product_id' => 733
),
array(
'product_name' => Example
)
);
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if (!empty($val['product_id']) && $val['product_id'] == $id) {
return "true"; // or return key according to your wish
}
}
return "false";
}
echo $found = searchForId(733, $items);
Output:- https://eval.in/805075
Reference taken:- https://stackoverflow.com/a/6661561/4248328
So I have a couple of associated arrays of equal length and associations, and need to compare them. If the voted key in the first array has a value, I need to update the voted key value in the second array with that same value.
// create the arrays...
$votes_array = [];
array_push($votes_array, array(
'id' => '1',
'voted' => '-1'
)
);
array_push($votes_array, array(
'id' => '1',
'voted' => ''
)
);
$menu_array = [];
array_push($menu_array, array(
'id' => '1',
'voted' => ''
)
);
array_push($menu_array, array(
'id' => '1',
'voted' => ''
)
);
I tried this but but couldn't even get the result to echo true.
foreach ($votes_array as $votes_array_key => $votes_array_value) {
foreach ($menu_array as $menu_array_key => $menu_array_value) {
if( $votes_array_key == 'voted' && ($votes_array_value == '1' || $votes_array_value == '-1') ){
echo 'true';
// Update the $menu_array array index with the associated 'voted' value.
}
}
}
So it would end up with $menu_array[0]['voted'] being '-1'.
How do I achieve this?
Thanks.
Edit:
I've also modified the accepted answer to cater for when the length of votes_array varies.
foreach($votes_array as $votes_key => $votes_vote) {
if( ! $votes_vote['voted'] )
{
continue;
}
else
{
$getVoteId = $votes_array[$votes_key]['id'];
foreach($menu_array as $menu_key => $menu_vote)
{
if($menu_array[$menu_key]['id'] == $getVoteId)
$menu_array[$menu_key]['voted'] = $votes_vote['voted'];
}
}
}
Assuming those are strings and arrays are equal in length like you said this would be simple one from top of the head:
foreach($votes_array as $key => $vote) {
if( ! $vote['voted']) continue;
$menu_array[$key]['voted'] = $vote['voted'];
}
It seems you set your voted keys, so im using empty instead of isset to check for a non-value.
foreach($votes_array as $key=>$vote) {
if (!empty($vote["voted"])) {
$menu_array[$key]["voted"] = $vote["voted"];
}
}
I was wondering when working with multimedional arrays, if a certain key is the same, is there a way to combine the contents of other keys into its own array if a certain key is the same?
Something like this:
// name is the same in both arrays
array(
array(
'name' => 'Pepsi',
'store' => 'Over here',
'number' => '1234567'
),
array(
'name' => 'Pepsi',
'store' => 'Over here',
'number' => '5556734'
)
)
into something like this
array(
array(
'name' => 'Pepsi',
'store' => array('Over here', 'Over here'),
'number' => array('1234567', '5556734')
)
)
The defining key is checking if the name element is the same for the other arrays.
You can try a function like this.
function mergeByKey($array,$key){
$tmp_array = array();
foreach ( $array as $k => $row ) {
$merged = false;
foreach ($tmp_array as $k2 => $tmp_row){
if ($row[$key] == $tmp_row[$key]){
foreach ( $row as $k3 => $value ) {
if ($k3 == $key) continue;
$tmp_array[$k2][$k3][] = $value;
$merged = true;
}
}
if ($merged) break;
}
if (!$merged) {
$new_row = array();
foreach ( $row as $k4 => $value ) {
if ($k4 == $key) $new_row[$k4] = $value;
else $new_row[$k4] = array($value);
}
$tmp_array[] = $new_row;
}
}
foreach ( $tmp_array as $t => $row ) {
foreach ( $row as $t2 => $value ) {
if ( count($value) == 1 && $t2 != $key ) $tmp_array[$t][$t2] = $value[0];
}
}
return $tmp_array;
}
passing the array as first parameter and the key as second one.
I'm referencing to your array structure
edited: missed a piece
edited2: if resultin array contains elements with one string, it returns a string and not a array with one element
demo
This function uses a given field name as the grouping identifier and turns all other fields into arrays.
Note that single occurrences of your field name will yield arrays with a single element for the other fields. I wasn't sure whether that's a desirable trait, but just making sure you know ;-)
$arr = array(
array(
'name' => 'Pepsi',
'store' => 'Over here',
'number' => '1234567'
),
array(
'name' => 'Pepsi',
'store' => 'Over here',
'number' => '5556734'
)
);
function mergeArray($array, $column)
{
$res = array();
foreach ($array as $item) {
foreach ($item as $key => $value) {
if ($key === $column) {
$res[$column][$key] = $value;
} else {
$res[$column][$key][] = $value;
}
}
}
return array_values($res);
}
print_r(mergeArray($arr, 'name'));
Demo
Thanks to Gianni Lovece for her answer but I was able to develop a much simpler solution based on this problem. Just plug in the $result_arr to browse through and the $key you want to use as basis and it immediately outputs a multidimensional array with non-repeating values for repeating elements (see example below).
function multiarray_merge($result_arr, $key){
foreach($result_arr as $val){
$item = $val[$key];
foreach($val as $k=>$v){
$arr[$item][$k][] = $v;
}
}
// Combine unique entries into a single array
// and non-unique entries into a single element
foreach($arr as $key=>$val){
foreach($val as $k=>$v){
$field = array_unique($v);
if(count($field) == 1){
$field = array_values($field);
$field = $field[0];
$arr[$key][$k] = $field;
} else {
$arr[$key][$k] = $field;
}
}
}
return $arr;
}
For example, in the sample array for this question, running multiarray_merge($mysample, 'name') returns
array(
'Pepsi' => array(
'name' => 'Pepsi',
'store' => 'Over here', // String: Not an array since values are not unique
'number' => array('1234567', '5556734') // Array: Saved as array since values are unique
)
);
It may just be that I've checked out already for the weekend, but having a bit of trouble updating an associative array based on a certain value. For example, here is what I have so far:
$slideshow_vars = array(
'js_animation' => $slideshow_options['js_animation'],
'js_slide_direction' => $slideshow_options['js_slide_direction'],
'js_slideshow' => $slideshow_options['js_slideshow'],
'js_slideshow_speed' => $slideshow_options['js_slideshow_speed'],
'js_animation_duration' => $slideshow_options['js_animation_duration'],
'js_direction_nav' => $slideshow_options['js_direction_nav'],
'js_control_nav' => $slideshow_options['js_control_nav'],
'js_keyboard_nav' => $slideshow_options['js_keyboard_nav'],
'js_mousewheel' => $slideshow_options['js_mousewheel'],
'js_prev_text' => $slideshow_options['js_prev_text'],
'js_next_text' => $slideshow_options['js_next_text'],
'js_pause_play' => $slideshow_options['js_pause_play'],
'js_pause_text' => $slideshow_options['js_pause_text'],
'js_play_text' => $slideshow_options['js_play_text'],
'js_randomize' => $slideshow_options['js_randomize'],
'js_slide_start' => $slideshow_options['js_slide_start'],
'js_animation_loop' => $slideshow_options['js_animation_loop'],
'js_pause_on_action' => $slideshow_options['js_pause_on_action'],
'js_pause_on_hover' => $slideshow_options['js_pause_on_hover'],
'js_controls_container' => $slideshow_options['js_controls_container'],
'js_manual_controls' => $slideshow_options['js_manual_controls'],
'js_start_function' => $slideshow_options['js_start_function'],
'js_before_function' => $slideshow_options['js_before_function'],
'js_after_function' => $slideshow_options['js_after_function'],
'js_end_function' => $slideshow_options['js_end_function']
);
foreach ($slideshow_vars as $key => $value) {
if($value == NULL) {
$value = "false";
}
}
print_r($slideshow_vars);
In a number of the values in the array, they are outputting NULL -- well, I need to change those to a string of false (this data is being localized and then sent to a JS file which expects false). When I perform the above print_r() it hasn't actually updated anything.
That is because foreach normally passes array fields by value.
What you need to do is this:
foreach ($slideshow_vars as $key => &$value) {
if($value == NULL) {
$value = "false";
}
}
You have to update arrays like this by using the canonical path:
$slideshow_vars[$key] = 'false';
Or what cyper mentioned by using ... as $key => &$value to pass the inner loop the reference of $value instead of just its value.
Each loop, $value is set to the value. By updating the value of $value, you're just changing it in the local scope, and not setting the value inside that array. For that, you want to reference the field and update it, as such:
foreach ($slideshow_vars as $key => $value) {
if($value == NULL) {
$slideshow_vars[$key] = "false";
}
}
If all of the keys are the same and you want to save yourself a lot of code, you could try experimenting with this:
$slideshow_vars = array_merge( // Merge two arrays:
// Create an array of the same keys, but all with values of "false"
array_combine(
array_keys( $slideshow_options),
array_fill( 0, count( $slideshow_options), "false")
),
// Remove values that equal false (may need to specify a more precise callback here)
array_filter( $slideshow_options)
);
This should give you the $slideshow_vars variable you're looking for.