Compare associative array with standard array values PHP - php

I have a set of ids and names in an associative array and in my other array I have my list of id's that I want to compare against the first list.
I'd like to be able to perform an intersection type search function without losing the names from the associative array.
I've though about doing a nested foreach, but it seems like this process could take forever as both arrays could potentially have 70k+ values.

$assoc = array(
'a' => 'one',
'b' => 'two',
);
$array = array('b', 'c', 'd');
$match = array_intersect_key($assoc, array_flip($array));
print_r($match);
outputs:
Array
(
[b] => two
)
which I believe is what you're after.

Related

Combine dynamic arrays with dynamic keys in to single arrays

I have this dynamic multiple arrays that I need to combine in one array and serialized them. The problem is I need to keep both key and value.
$arr = array($bet_option_id => $bet_option_name);
Here i need to keep both bet_option_id AND bet_option_name. Then this result output:
Array ( [997650802] => Over 2.5 )
Array ( [997650807] => Yes )
This need to be simply
Array
(
[997650802] => Over 2.5
[997650807] => Yes
)
As it's dynamic, sometimes not comes with just single array so apparently I couldn't get it working. I need to retrieve both bet_option_id & bet_option_name. Tried something like this:
$arr = array($bet_option_id => $bet_option_name); //This is where all array keys, values are stores
$result = array();
foreach ($arr as $array) {
$result = array_merge($result, $array);
}
Any inputs will be nice.
Rather than create individual arrays like...
$arr = array($bet_option_id => $bet_option_name);
If you first create an empty array ( like you do with $result)
$arr = array();
and then add each item in using
$arr[$bet_option_id] = $bet_option_name;
Then you don't need to manipulate the array after - just create it as you want it in the first place.
You could either do like Nigel Ren suggested which is the most elegant solution
In case that you do not have arrays that their keys are entirely numeric you may use array_merge. The quote following is from PHP array-merge
Example #2 Simple array_merge() example
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
Don't forget that numeric keys will be renumbered!
Array
(
[0] => data
)
Alternatively you can always join arrays together like this
$a1 = [ 997650802 => 'Over 2.5' ];
$a2 = [ 997650807 => 'Yes' ];
var_dump( $a1 + $a2 ); // result is [997650802 => 'Over 2.5',997650807 => 'Yes']
You can check more about Array Types and Array Operators

How to cut array into two

I am trying to separate an array into two separate arrays. For example, if I have an array like this
Array([0]=>Hello[1]=>I'm[2]=>Cam)
I want to split it into two arrays and add another string
Array1([0]=>Hello[1]=>There,)
Array2([0]=>I'm[1]=>Cam)
Then finally add the two together
Array([0]=>Hello[1]=>There,[2]=>I'm[3]=>Cam)
What would be the simplest way to do this?
I know I can use array merge to put the two together but I don't know how to separate them at a certain point.
I'm also doing this on a large file that will be constantly getting bigger, so I cant use array_chunk()
Looking at your end result goal, I think a shorter method to get your desired response is to use array_splice which lets you insert into a middle of an array....
$arrayVarOriginal = array('Hello', 'Im', 'Cam');
$arrayVarExtra = array('There');
array_splice($arrayVarOriginal, 1, 0, $arrayVarExtra);
This should send you back Array([0]=>Hello[1]=>There,[2]=>Im[3]=>Cam) like you wanted!
The above avoids having to split up the array.
HOWEVER
If you did want to do it the hard way, here is how you would...
$arrayVarOriginal = array('Hello', 'Im', 'Cam');
$array1stPart = array(arrayVarOriginal[0], 'There');
$array2ndPart = array_shift($array1stPart);
$finalArray = array_merge($array1stPart, $array2ndPart);
How? array_shift removes the first item from any array, so that how we get $array2ndPart.... and $array1stPart is even easier as we can just manually build up a brand new array and take the first item from $arrayVarOriginal which is at position 0 and add 'There' in as our own new position 1.
Hope that helps :)
array_shift, array_splice, and array_merge are what you need to look into.
Based from your question, here step-by-step to get what you want for your final output.
1) Split Array
$arr = array('Hello', 'I\'m', 'Cam');
$slice = count($arr) - 1;
$arr1 = array_slice($arr, 0, -$slice);
$arr2 = array_slice($arr,1);
so, you get two new array here $arr1 and $arr2
2) Add new string
$arr1[] = "There";
3) Finally, combine the array
$arr = array_merge($arr1, $arr2)
Here sample output when you print_r the $arr
Array
(
[0] => Hello
[1] => There
[2] => I'm
[3] => Cam
)
array_slice second parameter is position where you want split. So you can do this dynamically by count the array length.
$string = array("Hello","I'm","Cam");
$firstArray = array_slice($string ,0,1);
array_push($firstArray,"There,");
$secondArray = array_slice($string ,1,2);
echo "<pre>";
print_r($firstArray);
echo "==========="."<pre>";
print_r($secondArray);
echo "<pre>";
print_r(array_merge($firstArray,$secondArray));
//out put
Array
(
[0] => Hello
[1] => There,
)
===========
Array
(
[0] => I'm
[1] => Cam
)
Array
(
[0] => Hello
[1] => There,
[2] => I'm
[3] => Cam
)
Hope it will be worked for your requirement. If not or you need more specify regarding this you can clarify your need.

PHP Write to a Multidimensional Array at 2 points in time

I am working with a multidimensional array that I want to conditionally add keys to and am not getting the output I desire. At the core of the issue is the following code:
$data[$CSVKey] = array (
'key1' => $key1value,
);
$data[$CSVKey] = array (
'key2' => $key2value,
);
What I would expect to happen when I work with the array at a later time is that there would be a multidimensional array with both key 1 and key 2, but I am not getting that. when I work with it, I only see 'key2'. However when I change it to this:
$data[$CSVKey] = array (
'key1' => $key1value,
'key2' => $key2value,
);
I see the array as I desire. Can I not populate a multidimensional array this way?
You are replacing whatever value $data[$CSVKey] is each time you assign a new array.
You should just continue using your bracket notation to assign your values:
$data[$CSVKey]['key1'] = $key1value;
$data[$CSVKey]['key2'] = $key2value;
Or you could use array_merge() if you wanted to add more than one element to the array in one call:
$data[$CSVKey] = array_merge($data[$CSVKey], ['key1' => $key1value, 'key2' => $key2value])

How to define single and multidimensional array in PHP?

I am beginner in PHP programming. I want to know how to define single and multidimensional array in PHP.
There are a wide variety of ways to do this, all of which are well explained on the relevant PHP manual page.
However, in terms of some examples:
$singleArray = array(1, 2, 3);
$multiArray = array(array(1, 2, 3), array(4, 5, 6));
You of course can also use the following syntax:
$singleArray = $multiArray = array();
$singleArray[] = 1;
$singleArray[] = 2;
...
$multiArray[0][] = "Bob";
$multiArray[0][] = "Steve";
$multiArray[1][] = "Dave";
$multiArray[1][] = "Jack";
...
You can also provide you own keys (in addition to the numeric ones), such as:
$singleArray = array('first'=>1, 'second'=>2, 'third'=>3);
(Use array_keys to extract the keys from such an array.)
However, if you're just starting out, you really want to spend a bit of time reading the excellent online documentation, practising with the tutorials, etc. as this will be a lot faster that asking a multitude of questions on SO. :-)
Array elements in PHP can hold values of any type, such as numbers, strings and objects. They can also hold other arrays, which means you can create multidimensional, or nested, arrays.
Single dimensional Array :
$myArray = array(value1, value2, value3);
Multidimensional Array :
$myArray = array(
array( value1, value2, value3 ),
array( value4, value5, value6 ),
array( value7, value8, value9 )
);
Here, the top-level array contains 3 elements. Each element is itself an array containing 3 values.
Basically, there are three different types of arrays:
Numeric array – An array with a numeric ID key.
Multidimensional arrays – An array containing one or more arrays.
Associative arrays – An array where each ID key is associated with a value.
Read here for more about these types : Types of Arrays in PHP
Did you read the manual ?
Especially the exemples, like this one :
$fruits = array ( "fruits" => array ( "a" => "orange",
"b" => "banana",
"c" => "apple"
),
"numbers" => array ( 1,
2,
3,
4,
5,
6
),
"holes" => array ( "first",
5 => "second",
"third"
)
);

Accessing an associative array by integer index in PHP

I want to set the value of an associative array using the array index of the key/value pair. For example:
$my_arr = array( "bling" => "some bling", "bling2" => "lots O bling" );
$my_arr[1] = "not so much bling"; // Would change the value with key bling2.
How can this be accomplish this without using the key string?
Use array_keys.
$keys = array_keys($my_arr);
$my_arr[$keys[1]] = "not so much bling";
There is no correlation between numeric and associative index keys.
When you say you want to set the value of an associative array using the array index of the key/value, then you have to use the given key, setting $array[1] is not the same as setting $array['foo'].
Consider this array
print_r( array('foo', 'foo' => 'bar', 'baz', 'some' => 'value') );
This will give
Array
(
[0] => foo
[foo] => bar
[1] => baz
[some] => value
)
The foo is the second element in the array. That's the offset, but it has nothing to do with the index 1. As you can see, in that array above, index 1 is associated with baz. It is wrong to assume that just because foo is the first associative key it has anything to do with the actual numeric key 1. Just like some does not correlate to 2.
Likewise, for a mixed array like shown above, the solution with array_keys suggested elsewhere on this site will not work, because
print_r( array_keys(array('foo', 'foo' => 'bar', 'baz', 'some' => 'value')) );
will give
Array
(
[0] => 0
[1] => foo
[2] => 1
[3] => some
)
So when you do $array[$keys[1]] you are really doing $array['foo']. But if you wanted to access the second associative value in that array ('some'), you cannot do $array[$keys[2]] because that would evaluate to $array[1] and that's baz.
The Offset of an element is completely unrelated to it's key or value
print_r(
array(
100 => 'foo',
'foo' => 'bar',
50 => 'baz',
'some' => 'value'
)
);
really means
Array
( //key value offset/position
[100] => foo // 0
[foo] => bar // 1
[50] => baz // 2
[some] => value // 3
)
which means the element at offset 0 is foo although it's key is 100. If you want to extract elements from an array by offset, you have to use
$third = array_splice($array, 2, 1);
echo $third[0]; // baz
This would create an array holding only the element at the third position.
Or you could use an ArrayIterator. The ArrayIterator implements a Seekable interface that lets you seek to a specific position/offset in the array and then fetch that:
$iterator = new ArrayIterator($array);
$iterator->seek(3);
echo $iterator->current(); // value
Whilst array_keys() allows access to the nth key, array_values will give you the nth value.
<?php
$array = [
0 => 'Zero',
'1' => 'One',
'Two' => 'Two',
];
echo array_values($array)[2];
?>
will output 'Two'.
Is there an advantage of one over the other? Well, the only minor one I can see is the number of array accesses.
With array_keys() you need to 3.
Get the keys from the data array.
Get the nth key from the list of keys.
Get the value using the nth key from the data array.
With array_values(), you only need 2.
Get the values from the data array.
Get the nth value from the list of values.
But, on the other hand, keys are normally smaller and the data could be hugely nested, so, on balance, using the array_keys() is probably safer.
If the array is large, both array_keys and array_values will be wasteful since they will allocate a new array the same size as the original, just to get the nth key (or value).
array_slice accepts an integer offset and works on associative arrays. You can use it to get (and set) the nth key in constant time.
// This will at most allocate 2 temporary arrays of 1 element each
$key = array_keys(array_slice($array, $n, 1, true))[0];
$array[$key] = $value;
Try this. It works for you.
$result= array_values($my_arr); // Array with indexes you need
Another possibility is to convert it to a normal array:
$arraybuff = implode("~~~",$my_arr);
$my_arr = explode("~~~",$arraybuff);
Where "~~~" is a delimiter that wont occur in your data.
Now you can access the array using numerical indexes equal to the offsets.
If you still need to retain your associative array, just assign it to a different variable.

Categories