php array string key index - php

I have the following code:
$a = array();
$b = array('a', 'b');
for($i=0; $i<3; $i++){
$a[] = array($b[$i] => array(1, 2, 3));
}
print_r($a);
I get the following result:
Array
(
[0] => Array
(
[a] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
[1] => Array
(
[b] => Array
(
[0] => 1
[1] => 2
[1] => 3
)
)
)
This is what I'm trying to accomplish:
array (
'a' => array ( 1, 2, 3 )
'b' => array ( 1, 2, 3 )
)
What am I doing wrong? I don't want $a to add numeric elements, but rather contain a, b, c as the indexes. Any suggestions? Thanks

change the forloop to like this
for($i=0; $i<count($b); $i++){
$a[$b[$i]] =array(1, 2, 3);
}

You can do,
$a = array();
$b = array('a', 'b');
for($i=0; $i<3; $i++){
if(isset($b[$i])){
$a += array($b[$i] => array(1, 2, 3));
}
}
DEMO.

You can set the key for $a like so:
$a = array();
$b = array('a', 'b');
for($i=0; $i<count($b); $i++){
$a[$b[$i]] = array(1, 2, 3);
}
print_r($a);
Also, i changed your for loop to use count($b) as you where iterating 1 to many times with your hard coded 3

Try:
$a[$b[$i]] = array(1,2,3);

One more iteration..
$a = array();
$b = array('a', 'b');
for($i=0; $i<3; $i++){
$a[$b[$i]] = array(1, 2, 3);
}
print_r($a);

Let's check what you were doing wrong.
$a = array();
$b = array('a', 'b'); // Count of elements is 2
for($i=0; $i<3; $i++){ // this will loop 3 times assigning 0,1,2 to $i where. You only needed 0 and 1 for an array with 2 elements
$a[] = array($b[$i] => array(1, 2, 3)); // here you are adding a new element to $a without providing key. So it becomes a numeric indexed array.
}
Solution:
for($i=0; $i<count($b); $i++){ // you could use $i<2 as well however count($b) makes your code more dynamic and result won't be affected if no of elements in $b changes.
$a[$b[$i]] =array(1, 2, 3); // you put $b[$i] as key for $a which creates an associative array
}

Related

PHP - Ensure array has certain number of items

I have a PHP array which looks like this...
array
(
[0] => apple,
[1] => orange,
)
I need to ensure the array contains 4 items, so in the instance above I want to end up with this...
array
(
[0] => apple,
[1] => orange,
[2} => ,
[3] => ,
)
Am I best looping through this with a counter and creating a new array, or is there a better method?
Pad your array with elements to a size that you need:
$my_arr = [1,2];
$my_arr = array_pad($my_arr, 4, '');
This should do what you're after
$iNumberOfElements = 5;
$a = array('apple', 'orange');
if(count($a) < $iNumberOfElements){
while (count($a) < $iNumberOfElements) {
$a[] = "";
}
}
var_dump($a);
exit;
as #iainn said: php.net/manual/en/function.array-pad.php
there is this function:
$input = array(12, 10, 9);
$result = array_pad($input, 5, 0);
// result is array(12, 10, 9, 0, 0)
5 is the size of your array, 0 is the default value to empty cells

PHP Left rotate array in PHP

I am trying to left rotate an array in PHP 2 times. It works correctly but there is a blank space in the array from some unknown reason. This is my code:
$a_temp = fgets($handle);
$a = explode(" ",$a_temp);
for($i = 0; $i < 2; $i++){
print_r($a);
array_unshift($a, array_pop($a));
print_r($a);
}
The file has something like this:
1 2 3
Now the output I get is:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Array
(
[0] => 3
[1] => 1
[2] => 2
)
Array
(
[0] => 3
[1] => 1
[2] => 2
)
Array
(
[0] => 2
[1] => 3
[2] => 1
)
As you can see, every time a rotate is performed, it introduces a blank space in it and during printing the array, it appears as a new line character. Any ideas what I am doing wrong?
As pointed out by #cHao ans #Kulvar, your "3" element is in fact "3\n" because your line returned by fgets ends with a \n which is normal.
Replace $a = explode(" ",$a_temp); with $a = explode(" ",trim($a_temp)); and you're fixed. Works with any string, numeric or not
It seems you have a non-integer value in there. Use array_map() to cast all values to integers.
$a_temp = fgets($handle);
$a = explode(" ",$a_temp);
$a = array_map("intval", $a); //Cast all values to integers
for($i = 0; $i < 2; $i++){
print_r($a);
array_unshift($a, array_pop($a));
print_r($a);
}
https://eval.in/724912
Combine the array_push() and array_shift() function. In this solution you would have to input a number of rotations, or you change the $k variable in the for-loop to your desired amount of rotations.
for($i=0; $i<$k; $i++){
//remove first element
$firstElement = array_shift($a);
//push first element to the end
array_push($a, $firstElement);
}
echo implode(" ", $a);
The first method is the optimised code. But other two are solution but not optimise as the first one.
function rotate_left_method_1( $a, $d ) {
$first = array_slice( $a, 0, $d );
$second = array_slice( $a, $d, null );
return array_merge( $second, $first );
}
function rotate_left_method_2( $a, $d ) {
$swap = 1;
foreach ( $a as $v ) {
if ( $d >= $swap ) {
array_shift( $a );
array_push( $a, $v );
$swap ++;
}
}
return $a;
}
function rotate_left_method_3( $a, $d ) {
if ( is_array( $a ) ) {
for ( $swap = 0; $swap < $d; $swap ++ ) {
$temp = $a[0];
array_shift( $a );
array_push( $a, $temp );
}
}
return $a;
}
var_dump( rotate_left_method_1( array( 1, 2, 3, 4, 5 ), 4 ) );
var_dump( rotate_left_method_2( array( 1, 2, 3, 4, 5 ), 4 ) );
var_dump( rotate_left_method_3( array( 1, 2, 3, 4, 5 ), 4 ) );
function rotateLeft($d, $arr) {
$remaining = array_slice($arr, $d);
array_splice($arr, $d);
return array_merge($remaining,$arr);
}
$d =4; $arr = [1,2,3,4,5];
$result = rotateLeft($d, $arr);
var_dump($result);
output [5, 1, 2, 3, 4]

combine multiple arrays with order of key

For example I have like more than 3 different arrays, with element like below:
1st array
hello-1
hi-1
2nd array
ok-two
hi-2
22-two
hello
3rd array
hi-3rd
hello3
And so on...
I want to combine this array in the order one by one. For example the expected output for the 3 arrays above would be:
hello-1
ok-two
hi-3rd
hi-1
hi-2
hello3
22-two
hello
I tried array_merge(). But it appends the 2nd array after the complete 1st array, which is not what I'm looking for, so here I'm kinda stuck and don't know which functions I can use here. Any hints or ideas?
This should work for you:
First I get the first element of each array into a sub array, then the second value into the next sub array and so on, that you get this structure of array:
Array
(
[0] => Array
(
[0] => hello-1
[1] => ok-two
[2] => hi-3rd
)
//...
)
After this you can just loop through each array value with array_walk_recursive() and get every value into your array.
<?php
$arr1 = [
"hello-1",
"hi-1",
];
$arr2 = [
"ok-two",
"hi-2",
"22-two",
"hello",
];
$arr3 = [
"hi-3rd",
"hello3",
];
$arr = call_user_func_array("array_map", [NULL, $arr1, $arr2, $arr3]);
$result = [];
array_walk_recursive($arr, function($v)use(&$result){
if(!is_null($v))
$result[] = $v;
});
print_r($result);
?>
output:
Array
(
[0] => hello-1
[1] => ok-two
[2] => hi-3rd
[3] => hi-1
[4] => hi-2
[5] => hello3
[6] => 22-two
[7] => hello
)
I have another way to solve this issue
<?php
$arr1 = array(
"hello-1",
"hi-1");
$arr2 = array("ok-two",
"hi-2",
"22-two",
"hello");
$arr3 = array(
"hi-3rd",
"hello3");
$max = count($arr1);
$max = count($arr2) > $max ? count($arr2) : $max;
$max = count($arr3) > $max ? count($arr3) : $max;
$result = array();
for ($i = 0; $i < $max; $i++) {
if (isset($arr1[$i])) {
$result[] = $arr1[$i];
}
if (isset($arr2[$i])) {
$result[] = $arr2[$i];
}
if (isset($arr3[$i])) {
$result[] = $arr3[$i];
}
}
print_r($result);

To compare two arrays while considering duplicate value

i have two arrays
$array1 = array(1, 2, 2, 3);
$array2 = array( 1, 2, 3,4);
and when did :
var_dump(array_diff($array1, $array2));
getting :
array(0){}
as output , but i am looking for :
array(1){[2]=>2}
can someone please let me know how to do it
Thanks in Advance
Try this
$array1 = array(1, 2, 2, 3, 4, 5, 5, 7);
$array2 = array(1, 2, 4, 6, 3, 3, 5);
$diff = array_filter($array1,
function ($val) use (&$array2) {
$key = array_search($val, $array2);
if ( $key === false ) return true;
unset($array2[$key]);
return false;
}
);
print_r($diff);
// Array ( [2] => 2 [6] => 5 [7] => 7 )
If you want to count number of duplicate element from same array as well as from multiple arrays, please use below code,
<?php
$array1 = array(1,2,2,3,7);
$array2 = array(1,2,3,4);
$diff_array = array();
$diff_array1 = array_count_values($array1);
$diff_array2 = array_count_values($array2);
$a = array_keys($diff_array1);
$b = array_keys($diff_array2);
for($i=0;$i<count($a);$i++)
{
if($a[$i] == $b[$i])
{
$x = $a[$i];
$y = $b[$i];
$diff_array1[$x] += $diff_array2[$y];
}
}
$diff_array1=array_diff($diff_array1, array('1'));
echo '<pre>';
print_r($diff_array1);
?>
This will get you the desired result:
$array1 = array(1, 2, 2, 3);
$array2 = array( 1, 2, 3,4);
$countArray1 = array_count_values($array1);
$countArray2 = array_count_values($array2);
foreach($countArray1 as $value=>$count) {
if($count > 1) $dupArray[] = $value;
}
foreach($countArray2 as $value=>$count) {
if($count > 1) $dupArray[] = $value;
}
print_r($dupArray);
Result
Array
(
[0] => 2
)
Explanation
Using array_count_values will count all the values of an array, which would look like:
Array
(
[1] => 1
[2] => 2
[3] => 1
)
Array
(
[1] => 1
[2] => 1
[3] => 1
[4] => 1
)
We then iterate through each array_count_values to locate values that occur more than once. This will work when you have more than one set of duplicate values:
$array1 = array(1, 2, 2, 3);
$array2 = array( 1, 2, 3, 4, 3);
Result
Array
(
[0] => 2
[1] => 3
)
While it may be less elegant, the simple way to do this is with a for loop:
$diff_array = array();
for ($i = 0; ($i < count($array1)) and ($i < count($array2)); $i++)
{
if ($array1[$i] !== $array2[$i]) { $diff_array[$i] = $array1[$i]; }
}

How to make this format of array in PHP?

I want to make an array in PHP but it should be in specific format such this:
array(1, 5, 3)
I mean, I have the values 1, 5 and 3 from my database, so I had to loop it with the use of array_push
$a=array();
foreach( $db_nums as $db_num ){
array_push($a, $db_num);
}
print_r($a);
but it outputs:
Array ( [0] => 1 [1] => 5 [2] => 3 );
i want it to be only:
array(1, 5, 3 );
Any ideas how? Thanks a lot for any help!
Just use the below code:
$Array = array(1,2,3);
Edit:
$a = array();
foreach( $db_nums as $db_num )
{
$a[] = $db_num;
}
print_r($a);
$db_nums = array(1, 2, 3); //pointless example, but comes from DB
$a = array();
foreach ($db_nums as $n) {
$a[] = $n;
}
var_export($a);
That will output:
array (
0 => 1,
1 => 2,
2 => 3,
)
Which is about as close as you're going to get without writing your own function to do it.
(Also note that in this example, you could just directly do var_export($db_nums).)
<?php $array = array("foo", "bar", "hallo", "world"); var_dump($array); ?>
You can use that

Categories