How to define single and multidimensional array in PHP? - 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"
)
);

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 compare two arrays and add keys from one array to another

I have two arrays
1st array
first array containts 60 strings like this:
['string1','string2', ... , string60];
2nd array
And I have an associative array like this:
['Key' => value, ..., 'Key' => value]
What I need to do is compare each value from first array(that contains 60 ellements), with each key from the second array, and if second(associative) array doesn't contain key that matches any value from first array - I should add such ellement to the associative array.
For example second array doesn't have key that matches string5 for example, and I'm not talking about value of the key, I'm literally talking about Key itself. So now I need to add string5 as a new key => value ellement to the array, the Key must be the word string5, and the value must be empty.
What is the best way to do it?
Not more complicated than:
$combined = $array2 + array_fill_keys($array1, null);
array_fill_keys creates an array like ['string1' => null, ..], + adds all of these keys which don't already exists in $array2.
$combined = $array2 + array_fill_keys($array1, null);// key value will be maintained
array_values($array2); //index starts from 0
This should work
foreach($array_1 as $val) {
if(!isset($array_2[$val])) {
$array_2[$val] = null;
}
}
pretty sure there are people who know more efficient ways (resource wise) as this might take long when you have huge arrays.
Here is the logical way to do this.
First divide the second array in key and values array. I mean two different array.
So
$keys = array_keys($array2);
$values = array_values($array2);
now you have to take the different from $array1 to $array2 sigular or vice-versa ( Depends on your requirement ) and it will give you the difference of missing keys.
$diff = array_diff($array1,$keys);
Now you will be able to find it easily.
Please refer to array_diff Source: php.net
<?php
$required = array('key1', 'key2', 'key3','key4');
$data = array(
'key1' => 10,
'key2' => 20
);
$arrayDiff = array_diff_key(array_flip($required),$data);
$final = array_merge($data,$arrayDiff);
// Result
// Array
//(
// [key1] => 10
// [key2] => 20
// [key3] => 2
// [key4] => 3
//)
?>
If you want default value to be populated to the new keys added to the array, add below line before merge and use the variable $arrayFill instead of $arrayDiff in the merge statement
$arrayFill = array_fill_keys(array_flip($arrayDiff),0);

Check if Array has identical Entries

I got an array, with alot of entries, like:
$array = ['abc', 'def', 'ghi', 'abc'];
Now I wanna check, if there are identical entries in this array.
For example there is 'abc' twice in this array.
When I found identical entries, I wanna filter them out.
Whats the best way to do that without MySQL?
I could just check
if($array[0] == $array[1])
etc
but that would be horrible amount of work, and some bad programming i guess.
Greetings
You can just use array_unqique: http://www.php.net/manual/en/function.array-unique.php
Takes an input array and returns a new array without duplicate values.
Note that keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys. It does not mean that the key of the first related value from the unsorted array will be kept.
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
The above example will output:
Array
(
[a] => green
[0] => red
[1] => blue
)

Merging and array by value instead of key in PHP

I have two arrays of values that I would like to combine - but the only methods that PHP provides seem to combine by key instead of value. Here is a hack that I was able to use to get this to work, but I am wondering if there is a better method or a native function that I have missed. It's been a while since I last used arrays and it seems like there is an easy answer to this.
//Input arrays that we want to combine into one array
$array = array(2, 3, 4, 5);
$array2 = array(5, 6, 1);
//Flip values and keys
$array = array_flip($array);
$array2 = array_flip($array2);
//Combine array
$array3 = $array2 + $array;
//flip array keys back to values
$array3 = array_keys($array3);
//Optional sort
sort($array3);
print_r($array3);
Which returns the combined values of the two arrays:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
Not entirely sure what you are trying to accomplish. I am assuming you are trying to combine 2 arrays without having any duplicates. If this is the case then the following would work
$newarr = array_unique(array_merge($array, $array2));

Compare associative array with standard array values 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.

Categories