Switch keys and value and Preserve entries with no value - php

I have this array:
'tab1' => '',
'tab2' => '',
'tab3' => 'active'
I want to do array_flip to swap the keys with the values, but the entries with an empty value are not kept.
How do I let PHP assign integer keys for me (like with an indexed array)?
Thanks
Edit:
To clarify things a bit, this is what I want:
0 => 'tab1'
1 => 'tab2'
'active' => 'tab3'

Directly through array_flip it's not possible. I think you want like this:-
<?php
$array1 = array('tab1' => '','tab2' => '','tab3' => 'active');
$array2 = array();
foreach($array1 as $key =>$value){
if(empty($value)){ // Or $value ==''
$array2[] = $key;
}else{
$array2[$value] = $key;
}
}
echo "<pre/>";print_r($array2);die;
?>
Output:- http://prntscr.com/79ge6z

Related

Check if array doesn't have a key and create it dynamically

I need to check if the keys of an array match an array of keys, and if they don't match then they need to be created. While I managed to create the check I still need to return all keys that don't match in the in_array condition so that they can be added to the original array. How can I achieve this?
My current code:
$new_value = ['id','name','age'];
$keys = ['id','name','age','sex','height','weight'];
foreach($new_value as $new_value){
if(!in_array($new_value, $keys )){
$new_value["{$key}"] = '';
}
}
The desired result would be:
Array pre processing:
'id' => 1,
'name' => 'Ed',
'age' => 15,
Array post processing:
'id' => 1,
'name' => 'Ed',
'age' => 15,
'sex' => '',
'height' => '',
'weight' => '',
So, there are a couple of things here.
// When you are running through your foreach, you don't want to overwrite your
// array variable with the value, which is what is happening. Switch this to `new_values` (plural)
$new_values = ['id','name','age'];
$keys = ['id','name', 'age','sex','height','weight'];
// Since $keys is your desired structure, we want to loop through $key rather than $new_values, and add any missing keys to the $new_values
foreach($keys as $key){
// We want to check if $new_values has all the $keys (you were checking if $keys had all of $new_values, which it does already
if(!in_array($key, $new_values )){
// Since $key is already a string, we don't need to place it in quotes, just put the variable directly into the array as a new array item (because you are using an array of strings, the keys will be numerical)
$new_values[] = $key
}
}
If you are looking for a keyed array, so that you can get the value of $new_values['name'], then you will need to set your arrays up differently and do your checks differently. You can also use $keys to hold a default value.
// Set the keys for your array, instead of having an array of strings that is keyed numerically
$new_values = ['id' => 'user_id','name' => 'user name','age' => 'user age'];
$keys = ['id' => 'default_value','name' => 'default_value', 'age' => 'default_value','sex' => 'default_value','height' => 'default_value','weight' => 'default_value'];
// Here we'll get the key and value of each item in the $keys array
foreach($keys as $key => $default) {
// Check if the array key exists in new values and if not, set it to the predefined default value
if(!array_key_exists($key, $new_values) {
$new_values[$key] = $default;
}
}
EDIT
As per one of the comments on the answer, you could further simplify this with array_merge. If you want to throw an error or do something special on each field, you could use the loop. If you just want to fill in the blanks, it would work like:
// Set the keys for your array, instead of having an array of strings that is keyed numerically
$new_values = ['id' => 'user_id','name' => 'user name','age' => 'user age'];
$keys = ['id' => 'default_value','name' => 'default_value', 'age' => 'default_value','sex' => 'default_value','height' => 'default_value','weight' => 'default_value'];
// If you aren't going to be using the original $new_values array for anything, you can just overwrite it.
// As stated in the comment below, $new_values should be the second value, keys that are in both arrays will be overwritten by what's in the second array.
$new_values = array_merge($keys, $new_values);
// If you will be using the original $new_values array later in the code, you can set the output to a new variable
$filled_values = array_merge($keys, $new_values);
I'm not sure, but you can try next code:
<?php
$data = [
"id" => 1,
"name" => "Ed",
"age" => 15,
];
$keys = ["id", "name", "age", "sex", "height", "weight"];
$result = array_reduce(
$keys,
function ($data, $key) {
if (!isset($data[$key])) $data[$key] = '';
return $data;
},
$data
);
var_export($result);
PHP sandbox here

PHP: Find last occurence of string in array

I need to find the last found element of a specific value from an array. I giving an example in php of what I'm actually seeking for.
$Data = array(
'0' => 'car',
'1' => 'bike',
'2' => 'bus',
'3' => 'bike',
'4' => 'boat'
);
$key = array_search('bike', $Data) // it returns $key = 1 as result which the first element matched inside the array.
I want $key = 3 which is the last matched element.
Any suggestion appreciated.
PHP code demo
<?php
ini_set("display_errors", 1);
$Data = array(
'0' => 'car',
'1' => 'bike',
'2' => 'bus',
'3' => 'bike',
'4' => 'boat'
);
$toSearch="bike";
$index=null;
while($key=array_search($toSearch, $Data))
{
$index=$key;
unset($Data[$key]);
}
echo $index;
Here is the more simple and highly performace way. For it only calculate once, you can access it many time. The live demo.
$data = array_flip($Data);
echo $data['bike'];
after the flip, only keep the last element of the same elements. Here is the print_r($data)
Array
(
[car] => 0
[bike] => 3
[bus] => 2
[boat] => 4
)
We can use array_reverse to reverse array.
$key = array_search('bike', array_reverse($Data,true));
It will return 3.
you can use krsort to sort the array by key.
krsort($Data);
$key = array_search('bike', $Data);
echo $key;
Working example: https://3v4l.org/fYOgN
For this I am created one function it is very easy to use. You can pass only array and parameters.
function text_to_id($value, $arr_master) {
$id_selected = 0;
$search_array = $arr_master;
if (in_array($value, $search_array)) {
$id_selected = array_search($value, $search_array);
// pr($id_selected);exit;
}
if (!$id_selected) {
foreach ($search_array as $f_key => $f_value) {
if (is_array($f_value)) {
if (in_array($value, $f_value)) {
$id_selected = $f_key;
break;
}
} else if ($value == $f_value) {
$id_selected = $f_key;
break;
}
else;
}
}
return $id_selected;
}
this function use like this
$variable = text_to_id('bike', $your_array);

Loop over one array as if it was a multidimensional array

I have an array like:
$array = array(
'name' => 'Humphrey',
'email' => 'humphrey#wilkins.com
);
This is retrieved through a function that gets from the database. If there is more than one result retrieved, it looks like:
$array = array(
[0] => array(
'name' => 'Humphrey1',
'email' => 'humphrey1#wilkins.com'
),
[1] => array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
)
);
If the second is returned, I can do a simple foreach($array as $key => $person), but if there is only one result returned (the first example), I can't run a foreach on this as I need to access like: $person['name'] within the foreach loop.
Is there any way to make the one result believe its a multidimensional array?
Try this :
if(!is_array($array[0])) {
$new_array[] = $array;
$array = $new_array;
}
I would highly recommended making your data's structure the same regardless of how many elements are returned. It will help log terms and this will have to be done anywhere that function is called which seems like a waste.
You can check if a key exists and do some logic based on that condition.
if(array_key_exists("name", $array){
//There is one result
$array['name']; //...
} else {
//More then one
foreach($array as $k => $v){
//Do logic
}
}
You will have the keys in the first instance in the second yours keys would be the index.
Based on this, try:
function isAssoc(array $arr)
{
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
if(isAssoc($array)){
$array[] = $array;
}
First check if the array key 'name' exists in the given array.
If it does, then it isn't a multi-dimensional array.
Here's how you can make it multi-dimensional:
if(array_key_exists("name",$array))
{
$array = array($array);
}
Now you can loop through the array assuming it's a multidimensional array.
foreach($array as $key => $person)
{
$name = $person['name'];
echo $name;
}
The reason of this is probably because you use either fetch() or fetchAll() on your db. Anyway there are solutions that uses some tricks like:
$arr = !is_array($arr[0]) ? $arr : $arr[0];
or
is_array($arr[0]) && ($arr = $arr[0]);
but there is other option with array_walk_recursive()
$array = array(
array(
'name' => 'Humphrey1',
'email' => 'humphrey1#wilkins.com'
),
array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
)
);
$array2 = array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
);
$print = function ($item, $key) {
echo $key . $item .'<br>';
};
array_walk_recursive($array, $print);
array_walk_recursive($array2, $print);

Merge array with varying key value pairs

So I have various arrays which do not always have the same key/value pairs in them. What I want to do is to be able to merge the arrays, but to add in empty key/value pairs if they don't already exist in that array, but do in others. It's hard to explain but this might explain it better:
$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');
I need to somehow turn this into:
$finalArray = array(
array('name' => 'rory', 'car' => 'opel', 'dog' => ''),
array('name' => 'john', 'car' => '', 'dog' => 'albert')
);
I have been looking through PHP's documentation but can't find anything that will do this for me. Can anyone point me in the right direction? I don't even know an appropriate search term for what I want to achieve here, "array merge" isn't specific enough.
<?php
$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');
$diff1=array_diff(array_flip($arrayOne), array_flip($arrayTwo));
$diff2=array_diff(array_flip($arrayTwo), array_flip($arrayOne));
//array_flip flips the key of array with value
//array_diff would return the values in the first array that are not present in any of the other arrays inside
foreach ($diff2 as $s) {
$arrayOne[$s]="";
}
foreach ($diff1 as $s) {
$arrayTwo[$s]="";
};
//set key that didn't exist in that array as ""
$finalArray[]=$arrayOne;
$finalArray[]=$arrayTwo;
//add the arrays to the final array
print_r($finalArray);
Here's what I would do:
Merge your separate arrays into one (into a temporary var) using array_merge
Get the unique keys of this new array using array_keys
For each separate array, loop through the new keys array and add an empty value for each key that is not in the array. Then push the separate array into a final array.
<?php
$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');
$new = array_merge($arrayOne,$arrayTwo);
$new = array_keys($new);
$newarray = array();
foreach($new as $value){
$newarray[0][$value] = isset($arrayOne[$value]) ? $arrayOne[$value] : '' ;
$newarray[1][$value] = isset($arrayTwo[$value]) ? $arrayTwo[$value] : '' ;
}
echo "<pre>";print_r($newarray);
You can also use this short answer
$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');
$defaults = array('name' => '','car' => '','dog' => '');
$arrayOne += $defaults;
$arrayTwo += $defaults;
$newarray = array($arrayOne,$arrayTwo);
echo "<pre>";print_r($newarray);
Basing on what Justin Powell outlined, I managed to come up with this code before the other two code examples were posted (thank you mamta & user6439245).
I also needed to take the keys containing numbers and sort them appropriately, otherwise my keys would've been indexed like employer_1, education_1, employer_2, education_2.
// get the initial form entries data
$entries = array(
array('name' => 'john', 'car' => 'fiat', 'employer_1' => 'tangerine', 'education_1' => 'hideaways', 'education_2' => 'extras'),
array('name' => 'rory', 'car' => 'opel', 'employer_1' => 'sagittarius', 'employer_2' => 'tangerine', 'employer_3' => 'thehideout', 'education_1' => 'knatchbull')
);
// create an empty array to populate with all field keys
$mergedKeys = array();
// push all field keys into the array
foreach($entries as $entry){
foreach($entry as $key => $value){
array_push($mergedKeys, $key);
}
}
// remove duplicate keys from the array
$uniqueMergedKeys = array_unique($mergedKeys);
// create a new array to populate with the field keys we need to sort - the ones with numbers in
$keysToSort = array();
// push the number-containing keys into the array
$i=0;
foreach($uniqueMergedKeys as $uniqueKey){
if(1 === preg_match('~[0-9]~', $uniqueKey)){
array_push($keysToSort, $uniqueKey);
}
$i++;
}
// remove the number containing keys from the unique keys array
$uniqueMergedKeys = array_diff($uniqueMergedKeys, $keysToSort);
// sort the keys that need sorting
sort($keysToSort);
// put the newly sorted keys back onto the original keys array
foreach($keysToSort as $key){
array_push($uniqueMergedKeys, $key);
}
$final = array();
$i = 0;
foreach($entries as $entry){
foreach($uniqueMergedKeys as $key){
//if($entries[$i][$key]){
if (array_key_exists($key, $entries[$i])) {
$final[$i][$key] = $entries[$i][$key];
} else {
$final[$i][$key] = '';
}
}
$i++;
}
echo '<pre>'; print_r($final); echo '</pre>';

How do i get the key of an array element if i only have the value?

How do i get the key of an array element if i only have the value?
So i have this array and i need the key of an email address with the value
$users_emails = array(
'Spence' => 'spence#someplace.com',
'Matt' => 'matt#someplace.com',
'Marc' => 'marc#someplace.com',
'Adam' => 'adam#someplace.com',
'Paul' => 'paul#someplace.com');
How do i get the 'Adam' if all i have is the value 'adam#someplace.com'.. so basically how do i get the key if i have the value
Use array_search and this question.
Example from docs:
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
PHP has wonderful documentation and it's quite easy to find the basic stuff with Google.
<?php
$key = array_search('matt#someplace.com', $users_emails); // $key = 'Spence';
?>
$email = 'adam#someplace.com';
$name = array_search($email, $users_emails);
var_dump($name === 'Adam');
See array_search()
Use array_search
$key = array_search('adam#someplace.com', $users_emails);

Categories