Get first number in array list - php

I use laravel. And then when from submitted, it pass value as array.
My question is, how i can split the value? I want number before '-' and after '-'.
I want just like below:
and
My code just like below
$form = $request->all();
$emelto = $form['emelto'];
$split = explode('-', $emelto );
but it shows error
explode() expects parameter 2 to be string, array given
Please someone can help me.

Explode each individual string as you tried.
Insert each number in it's respective column index in result.
Snippet:
<?php
$emelto = [
'4-2',
'11-5'
];
$data = [];
foreach($emelto as $str){
foreach(explode('-',$str) as $index => $s){
$data[$index] = $data[$index] ?? [];// assuming your PHP version supports ??
$data[$index][] = $s;
}
}
print_r($data);

You can use
$array1 = array();
$array2 = array();
foreach($request->emelto as $val){
$dataArray = explode('-', $val);
$array1[] = $dataArray[0];
$array2[] = $dataArray[1];
}

$emelto is an array and you are passing it to explode. You have to pass it like $emelto[0].
You should update your code with the below one.
<?php
$form = $request->all();
$emelto = $form['emelto'];
$array1 = explode('-', $emelto[0] );
$array2 = explode('-', $emelto[1] );
$array3 = array();
array_push($array3, $array1[0]);
array_push($array3, $array2[0]);
$array4 = array();
array_push($array4, $array1[1]);
array_push($array4, $array2[2]);
?>

Related

PHP filter links

i have this array
$array = array(
"http://www.mywebsite.com/eternal_link_1",
"http://www.mywebsite.com/eternal_link_2/",
"http://www.mywebsite.com/eternal_link_1/#",
"http://subdomain1.mywebwite.com",
"http://subdomain2.mywebwite.com/eternal_link",
"http://www.external-link.com"
);
$eternal_links = array();
$subdomain_links = array();
$external_links = array();
how i can filter $array and add the values to the 3 arrays above?
You can use strpos to find the correct string.
foreach($array as $item){
if(strpos($item, 'external') == TRUE){
array_push($external_links, $item);
}
// and go on..
}

Similar values in php array

I have an array that stores some values. I'm trying to detect the similar values and add them to new array.
example:
$arrayA = array( 1,4,5,6,4,2,1);
$newarray = (4,1);
Any help?
Use the array_intersect() method. For example
$arrayA = array(1,4,5,6,4,2,1);
$arrayB = array(4,1);
$common_values = array_intersect($arrayA, $arrayB);
try this:
$array = array(1,4,5,6,4,2,1);
$duplicates = array_unique(array_diff_assoc($array, array_unique($array)));
$a1 = array( 1,4,5,6,4,2,1);
$a = array();
foreach($a1 as $value){
if(!in_array($value, $a)){
$a[] = $value;
}
}
$arrayA = array(1,4,5,6,4,2,1);
$newarray = array_diff_assoc($arrayA, array_unique($arrayA));

Merge complex array php

I have a site developed in php (codeigniter) and I want to merge some array with same structure.
This is the constructor of my array:
$first = array();
$first['hotel'] = array();
$first['room'] = array();
$first['amenities'] = array();
/*
Insert data into $first array
*/
$second = array();
$second['hotel'] = array();
$second['room'] = array();
$second['amenities'] = array();
/*
Insert data into $second array
*/
After insert data I want to merge this array but the problem is that I have subarray inside it and I want to create a unique array like that:
$total = array();
$total['hotel'] = array();
$total['room'] = array();
$total['amenities'] = array();
This is the try to merge:
$total = array_merge((array)$first, (array)$second);
In this array I have only the $second array why?
Use the recursive version of array_merge called array_merge_recursive.
It seems like array_merge doesn't do what you think it does: "If the input arrays have the same string keys, then the later value for that key will overwrite the previous one." Try this:
function merge_subarrays ($first, $second)
$result = array();
foreach (array_keys($first) as $key) {
$result[$key] = array_merge($first[$key], $second[$key]);
};
return $result;
};
Then call it as:
$total = merge_subarrays($first, $second);
and, if I've correctly understood your question, $total will contain the result you're looking for.
There is no standard way of doing it, you just have to do something like:
<?php
$first = array();
$first['hotel'] = array('hello');
$first['room'] = array();
$first['amenities'] = array();
/*
Insert data into $first array
*/
$second = array();
$second['hotel'] = array('world');
$second['room'] = array();
$second['amenities'] = array();
$merged = array();
foreach( $first as $key => $value )
{
$merged[$key] = array_merge( $value, $second[$key] );
}
print_r( $merged );

combine strings into an array in php

I have a web service to identify people and their functions from an external database that returns me a set of data if the login is successful. The data (that interests me right now) is separated in different strings as follow:
$groups="group1, group2, group3"
$functions="member, member, admin"
The first element of the string $groups corresponds to the first element of the $functions string.
We can have empty spots in the strings:
$groups="group1,, group3";
$functions="member,, admin";
What is the best way to combine them to obtain:
$usertype(
group1=>member,
group2=>member,
group3=>admin,
);
Then I plan to use array_search() to get the name of the group that corresponds to a function.
This is very trick especially when the first element is empty but here is a comprehensive solution
What you need is :
// Your Varriables
$groups = "group1,, group3";
$functions = "member,, admin";
// Break Into Array
$groups = explode(",", $groups);
$functions = explode(",", $functions);
// Combine both new Arrays and Output Result
$new = array_combine($groups, $functions);
print_r($new);
If you need to fix null values then :
Example :
// Your Varriables
$groups = "group1,, group3";
$functions = "member,, admin";
// Break Into Array
$groups = explode(",", $groups);
$functions = explode(",", $functions);
// Fix Null Values
$groups = fixNull($groups, true);
$functions = fixNull($functions);
// Combine both new Arrays and Output Result
$new = array_combine($groups, $functions);
print_r($new);
Output
Array
(
[group1] => member
[group2] => member
[group3] => admin
)
See Live DEMO
More Complex:
// Your Varriables
$groups = ",,, group3";
$functions = ",member,, admin";
// Fix Null Values
$groups = fixNull(explode(",", $groups), true);
$functions = fixNull(explode(",", $functions));
// Combine both new Arrays and Output Result
$new = array_combine($groups, $functions);
print_r($new);
Output
Array
(
[group4] => member
[group5] => member
[group6] => member
[group3] => admin
)
Live DEMO
Function Used
function fixNull($array, $inc = false) {
$ci = new CachingIterator(new ArrayIterator($array), CachingIterator::FULL_CACHE);
if ($inc) {
$next = array_filter($array);
$next = current($next);
$next ++;
} else {
$next = array_filter($array);
sort($next);
$next = end($next);
}
$next || $next = null;
$modified = array();
foreach($ci as $item) {
$modified[] = empty($item) ? trim($next) : trim($item);
if (! $ci->getInnerIterator()->current()) {
$item || $item = $next;
$next = $inc ? ++ $item : $item;
}
}
return $modified;
}
$groups = explode(",", $groups);
$functions = explode(",", $functions);
//then use the elements of the $groups array as key and the elements of the $functions array as the value
$merged = array_combine($groups, $functions);
Something along the lines of this should help:
$usertype = array_combine(explode(',', $groups), explode(',', $functions));
Use explode() to make arrays of your strings, and array_combine() to use one array as keys, the other one as values.
$groups = "group1, group2, group3";
$functions = "member, member, admin";
$usertype = array_combine(explode(", ", $groups), explode(", ", $functions));
Have you tried a explode($delimiter , $string) and then filter the array? I think that would be a good way of doing it:
$groups="group1,, group3";
$functions="member,, admin";
$groups_array = array_map('trim',explode(',', $groups));
$functions_array = array_map('trim',explode(',', $functions));
$final = array();
for ($i = 0; $i <= count($groups_array); $i++) {
$final[$groups_array[$i]] = $functions_array[$i];
}
$merged = array_combine($groups_array, $functions_array);
Demo
$groups="group1, group2, group3"
$functions="member, member, admin"
preg_match_all('/\w+/', $groups, $groups);
preg_match_all('/\d+/', $functions, $functions);
$final = array();
foreach ($groups[0] AS $key => $letter)
$final[] = $letter . '=>' . $functions[0][$key];
echo join(', ', $final);
explode and array_combine.
Note that you have a problem with whitespaces. Therefore use the following:
<?php
$groups="group1, group2, group3";
$functions="member, member, admin";
$groupArray = array_map(function($element){return trim($element);},
explode(',',$groups)); // split into array and remove leading and ending whitespaces
$functionArray = array_map(function($element){return trim($element);},
explode(',',$functions)); // split into array and remove leading and ending whitespaces
print_r(array_combine($groupArray,$functionArray));
?>
This will output:
Array
(
[group1] => member
[group2] => member
[group3] => admin
)
EDIT: removed trim for the possibility that the first element is empty.

Creating array from string

I need to create array like that:
Array('firstkey' => Array('secondkey' => Array('nkey' => ...)))
From this:
firstkey.secondkey.nkey.(...)
$yourString = 'firstkey.secondkey.nkey';
// split the string into pieces
$pieces = explode('.', $yourString);
$result = array();
// $current is a reference to the array in which new elements should be added
$current = &$result;
foreach($pieces as $key){
// add an empty array to the current array
$current[ $key ] = array();
// descend into the new array
$current = &$current[ $key ];
}
//$result contains the array you want
My take on this:
<?php
$theString = "var1.var2.var3.var4";
$theArray = explode(".", $theString); // explode the string into an array, split by "."
$result = array();
$current = &$result; // $current is a reference to the array we want to put a new key into, shifting further up the tree every time we add an array.
while ($key = array_shift($theArray)){ // array_shift() removes the first element of the array, and assigns it to $key. The loop will stop as soon as there are no more items in $theArray.
$current[$key] = array(); // add the new key => value pair
$current = &$current[$key]; // set the reference point to the newly created array.
}
var_dump($result);
?>
With an array_push() in the while loop.
What do you want the value of the deepest key to be?
Try something like:
function dotToArray() {
$result = array();
$keys = explode(".", $str);
while (count($keys) > 0) {
$current = array_pop($keys);
$result = array($current=>$result);
}
return $result;
}

Categories