Best way to refer index which contains in array - php

In php I'm willing to check the existence of indexes that match with another values in array.
$indexes = array("index", "id", "view");
$fields = array(
"index" => 5,
"id" => 7,
"form" => 10,
"date" => 10,
);
MY ideal result is, in this case, to get "form" and "date". Any idea?

Try
$fields_keys = array_keys($fields);
$fields_unique = array_diff($fields_keys, $indexes);
The result will be an array of all keys in $fields that are not in $indexes.

You can try this.
<?php
$indexes = array("index", "id", "view");
$fields = array(
"index" => 5,
"id" => 7,
"form" => 10,
"date" => 10,
);
$b = array_diff(array_keys($fields), $indexes);
print_r($b);

You can use array_keys function to retrieve keys of a array
Eg:
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
Outputs
Array
(
[0] => 0
[1] => color
)
PHP Documentation

Your question is a little unclear but I think this is what you're going for
array_keys(array_diff_key($fields, array_fill_keys($indexes, null)));
#=> Array( 0=>"form", 1=>"date" )
See it work here on tehplayground.com
array_keys(A) returns the keys of array A as a numerically-indexed array.
array_fill_keys(A, value) populates a new array using array A as keys and sets each key to value
array_diff_key(A,B) returns an array of keys from array A that do not exist in array B.
Edit turns on my answer got more complicated as I understood the original question more. There are better answers on this page, but I still think this is an interesting solution.

There is probably a slicker way than this but it will get you started:
foreach(array_keys($fields) as $field) {
if(!in_array($field, $indexes)) {
$missing[] = $field;
}
}
Now you will have an array that holds form and date.

Related

How to get values of array 1 and array 2 based on array index of array3 in laravel/php? [duplicate]

I wrote this function to get a subset of an array. Does php have a built in function for this. I can't find one in the docs. Seems like a waste if I'm reinventing the wheel.
function array_subset($array, $keys) {
$result = array();
foreach($keys as $key){
$result[$key] = $array[$key];
}
return $result;
}
I always want this too. Like a PHP version of Underscore's pick.
It's ugly and counter-intuitive, but what I sometimes do is this (I think this may be what prodigitalson was getting at):
$a = ['foo'=>'bar', 'zam'=>'baz', 'zoo'=>'doo'];
// Extract foo and zoo but not zam
print_r(array_intersect_key($a, array_flip(['foo', 'zoo'])));
/*
Array
(
[foo] => bar
[zoo] => doo
)
*/
array_intersect_key returns all the elements of the first argument whose keys are present in the 2nd argument (and all subsequent arguments, if any). But, since it compares keys to keys, I use array_flip for convenience. I could also have just used ['foo' => null, 'zoo' => null] but that's even uglier.
array_diff_key and array_intersect_key are probably what you want.
There is no direct function I think in PHP to get a subset from an array1 with compare to another array2 where the values are the list of key name which we fetch.
Like: array_only($array1, 'field1','field2');
But this way can be achieved the same.
<?php
$associative_array = ['firstname' => 'John', 'lastname' => 'Smith', 'DOB' => '2000-10-10', 'country' => 'Ireland' ];
$subset = array_intersect_key( $associative_array, array_flip( [ 'lastname', 'country' ] ) );
print_r( $subset );
// Outputs...
// Array ( [lastname] => Smith [country] => Ireland );

PHP Definition MultiDimensional Associative Arrays

I have 2 arrays with some sample data and I just want to confirm if I have the terminology correct:
Multidimensional Array:
$names = array([
"name" => "Bob",
"age" => 25,
"level" => 6],
["name" => "Joe",
"age" => 34,
"level" => 6]
);
Multidimensional Associative Array:
$names = array(
"Bob" => array(
"age" => 25,
"diploma" => "DAC",
"level" => 6),
"Joe" => array(
"age" => 34,
"diploma" => "DAC",
"level" => 6)
);
The second is Associative because of the index being the name rather than an index number and MultiDimensional because it has more than one entry.
I know it is not really a programming question requiring a code solution, I am just learning the terminology.
I add my two cents. All said by others is pretty correct, but:
The main difference from associative arrays and "simple" arrays. With "simple" arrays you can do something like this
for( $i = 0; $i < count( $array ) - 1; $i++ ) {
$element = $array[ $i ];
// Do something with $element
}
With associative arrays, you cannot do it and, if you want to traverse all the arrays you have to do something like this
foreach( $array as $key => $element ) {
// Do something with $element
}
This approach (the foreach) can be applied to the "simple" array too, while the first can be applied ONLY to "simple" array
Multidimensional array are simply arrays with AT LEAST one element that is an array, no matter the "type"
By the way, it's always think about arrays as associative arrays, always. It prevents you some very simple mistakes later on
Both arrays are multidimensional associative array.
But in second array you can get details of Bob or Joe by just using their name as key. For example to get details of Bob you can just call:
$names['Bob']
In first array you have to know the id or index of array to which Bob details were stored.

Get array element by value in similar way like getting by $key

Is there a possibility in PHP to get an array element by it's value. What I wan't to do is to update an element without knowing the key but nowing it's value:
$translations = array(
"en" => 123,
"de" => 456,
"es" => 789,
"fr" => 901
);
i know that what i wan't to do can be done with an foreach loop:
foreach($translations as $lang=>$id):
if($id == 123) $translations[$lang] = 0;
endforeach;
But is there any possibility to avoid this loop and to automatically set it?
You are looking for array_search():
if(false!==($key = array_search(123, $translations)))
{
$translations[$key] = 0;
}
-be aware that value can be non-unique, so array_search() will find only first key. If you need all of them, you'll have to either iterate through array with foreach or use something like array_walk()
You should use this :
$translations[array_search('123', $translations)] = 0;
Edit: use the solution proposed by Alma Do Mundo, he is right about checking the return value
You can do it in this way also.
Use array_keys function with search_values parameter. It will give you the array of keys which are having these values. Then you can update the original array based on the new array.
It will take care of all the duplicate values also.
$translations = array(
"en" => 123,
"de" => 456,
"es" => 789,
"fr" => 901,
"it" => 123
);
$arr=array_keys($translations,$seach_value);
if(count($arr)){
foreach($arr as $key => $value){
$translations[$value]=$new_value;
}
}

Can I store an array within a multidimensional array? (PHP)

It is possible to put an array into a multi dim array? I have a list of user settings that I want to return in a JSON array and also have another array stored in that JSON array...what is the best way to do that if it isn't possible?
A multi dimension is already an array inside an array. So there's nothing stopping you from putting another array in there. Sort of like dreams within dreams :P
Just use associative arrays if you want to give your array meaning
array(
'SETTINGS' => array(
'arr1' => array( 0, 1),
'arr2' => array( 0, 1)
),
'DATA' => array(
'arr1' => array( 0, 1),
'arr2' => array( 0, 1)
)
)
EDIT
To answer your comment, $output_files[$file_id]['shared_with'] = $shared_info; translates to (your comment had an extra ] which I removed)
$shared_info = array(1, 2, 3);
$file_id = 3;
$output_files = array(
'3' => array(
'shared_with' => array() //this is where $shared_info will get assigned
)
);
//you don't actually have to declare it an empty array. I just did it to demonstrate.
$output_files[$file_id]['shared_with'] = $shared_info; // now that empty array is replaced.
any array key can have an array value in php, as well as in json.
php:
'key' => array(...)
json:
"key" : [...]
note: php doesn't support multidimensional arrays as in C or C++. it's just an array element containing another array.

Transform string from associative array into multidimensional array

I'm storing images links into the database separating them with ,, but I want to transform this string into an array, but I'm not sure how to do it.
So my array looks like this:
$array = array(
"name" => "Daniel",
"urls" => "http:/localhost/img/first.png,http://localhost/img/second.png"
);
So I'd like to have it in the following form:
$array2 = array(
"name" => "Daniel",
"urls" => array("http:/localhost/img/first.png",
"http://localhost/img/second.png" )
);
I haven't been PHP'ing for a while, but for that simple use-case I would use explode.
$array['urls'] = explode(',', $array['urls']);
Uncertain if I interpreted your question correct though?
You can use array_walk_recursive like in the following example.
function url(&$v,$k)
{
if($k=='urls') {
$v = explode(",",$v);
}
}
$array = array(
"name" => "Daniel",
"urls" => "http:/localhost/img/first.png,http://localhost/img/second.png"
);
array_walk_recursive($array,"url");
You can check the output on PHP Sandbox

Categories