PHP - Extract second last value in array - php

I have the following array:
["theme","1,strand","Medical Ethics and Law,strandyear","Year 3"]
How can I extract the second last value in the array, then the second part of that value after the comma e.g. "Medical Ethics and Law,strandyear"?
This should result, for example, in 'strandyear'.
The actual value, not the position from the end, will be different for other arrays.
PHP 5.3.3...

What about the following ...
$secondLast = array_slice($source, -2, 1);
The PHP function array_slice can do the job in one line of code.
Then you 've got the second last entry from the original array. Now you can explode the string with a comma.
$parts = explode(",", $secondLast);
$strand = array_pop($parts);
The first line explodes the string by a comma. The second line gives you the last part (strand) of all exploded parts.

Try This,
First do json_decode()
then get secondLast then do strstr() to get value after comma and the do ltrim() thats it.
$str = '["theme","1,strand","Medical Ethics and Law,strandyear","Year 3"]';
echo $str;
$array = json_decode($str);
$secondLast = $array[2];//count($array)-2
echo'<pre>';print_r($array);
echo $secondLast.'<pre>';
echo ltrim(strstr($secondLast, ','),',');
die;
OUTPUT:
["theme","1,strand","Medical Ethics and Law,strandyear","Year 3"]
Array
(
[0] => theme
[1] => 1,strand
[2] => Medical Ethics and Law,strandyear
[3] => Year 3
)
Medical Ethics and Law,strandyear
strandyear

Best way to get the second last value in the array
end($array);
$second_last = prev($array);
after that you cant get the second part i.e the value after comma you can use
explode(separator,string) //function in PHP
$temp= explode(',', $second_last);//converted to an array
$second_part=$temp[1];

<?php
$a = ["theme","1,strand","Medical Ethics and Law,strandyear","Year 3"];
$b = explode(',',$a[1]);
$c = $b[1];
var_dump($c);
// tring(6) "strand"

Use explode explode
Returns an array of strings, each of which is a substring of string
formed by splitting it on boundaries formed by the string delimiter.
usage: explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] ) : array
$arr = Array("theme","1,strand","Medical Ethics and Law,strandyear","Year 3");
$secondValueAfterComma = explode(',',$arr[2]);
echo $secondValueAfterComma[1];

You may do like
$arr = ["theme","1,strand","Medical Ethics and Law,strandyear","Year 3"];
Here is your code to access 2nd last element
$value = $arr[count($arr)-2];

Related

How to Remove Elements from array in php after some given character?

I want to Remove all the Elements from my array which is after , but I am unable to do this.
I have an array like this => ["18-08-2022, 05:08:23pm","18-08-2022, 05:09:05pm"]
and I want to print array something like this => ["18-08-2022","18-08-2022"]
I want to remove Elements after the ,
This is what I tried
<?php
while ($row = mysqli_fetch_array($result)) {
$Etime[] = $row["Etime"];
$Etime1[]=$row["Etime"];
$E2[]=substr($Etime1[],',',true);
}
$Etime = json_encode($Etime);
$Etime1=json_encode($Etime1);
echo $Etime1
?>
this is easy-
steps to do so-
1.Parse your array as string.
2.store that in a variable.
3. then use a if loop and use php explode funtion. explode function will seperate that string elements by the seperator in this case the "," you want to remove.
explode(string $separator, string $string)
where,
separator-The boundary string.
string-The input string.
limit
example=
$text = "hello,there";
//using explode-
var_dump( explode( ',', $input2 ) );
output=
array(2)
(
[0] => string(5) "hello"
[1] => string(5) "there"
)
more about explode() here- https://www.php.net/manual/en/function.explode.php
Here's a simple php that generates the output you want. Since you only need date bits I have provided you with only the date bits. You can get general idea from here
$arr = ["18-08-2022, 05:08:23pm","18-08-2022, 05:09:05pm"];
//
// sample output: [ "18-08-2022", "18-08-2022" ]
//
$dateMappedToYourFormat = array_map(function($dt) {
return explode(",", $dt)[0]; // getting everything before comma
}, $arr);
echo implode(",", $dateMappedToYourFormat); //to view your result

how do i get data from csv and put in variable and get only the value that i want

Example
I have CSV file that contains data of random number example data in CSV :
639123456789,73999999999,739222222222,839444444444,8639555555555....more
So, if I upload it, I want it to explode in a variable or in an array as long as I get the specific data. example of data I want to get is all 2 first line starting at 73 be extract so meaning all numbers that start with 73 only.
Example: 73999999999,739222222222
I have tried it by using only 1 number using split,substr and explode function but my problem is if the user input a CSV bulk data with no limit.
You can use substr() and loop through your array deleting the elements that do not match.
$str = '639123456789,73999999999,739222222222,839444444444,8639555555555';
$array = explode(',', $str); //Convert your string to an array.
$searchString = '73'; //Set the value your looking for.
foreach($array as $key=>$value){
if(substr($value, 0, 2) != $searchString){ //This will test first two characters.
unset($array[$key]);
}
}
$array = array_values($array);
print_r($array);
This will output:
Array
(
[0] => 73999999999
[1] => 739222222222
)
Updated
This will make a new array with only the numbers you want in it, leaving the original array untouched.
$str = '639123456789,73999999999,739222222222,839444444444,739222222222,839444444444,839444444444,73999999999';
$array = explode(',', $str);
$searchString = '73';
foreach($array as $key=>$value){
if(substr($value, 0, 2) == $searchString){
$results[] = $value;
}
}
print_r($results);

Grouping in PHP using a character

I have an array like:
array{
0 => string 'B.E - ECE',
1 => string 'B.E - EEE',
2 => string 'Msc - Maths',
3 => string 'Msc - Social',
}
So how can I make the array into groups like:
B.E. => ECE, EEE
Msc => Maths,Social
?
I want to do it in PHP. Can anybody help me how to achieve it ?
So is your array split by the "-" character?
so it's Key - Value pairs split by commas?
Ok -
(edit: section removed to clarify answer)
Following conversation and some rearrangement of the question, a second try at a solution, with the above assumptions, try this:
$array = array {
0 => string 'B.E - ECE' (length=9)
1 => string 'B.E - EEE' (length=9)
2 => string 'Msc - Maths' (length=11)
3 => string 'Msc - Social' (length=12)
}
foreach ($array as $row){
$piece = explode("-",$row);
$key = $piece[0];
$newArray[$key][] = $piece[1];
unset($piece);
}
unset($row) ///tidy up
This will output two arrays each of two arrays:
$newArray[Msc] = array("Maths","Social");
$newArray[B.E] = array("ECE","EEE");
What I did was cause the Foreach loop to automatically add onto the array if the key exists with $newArray[$key][] so that the values are automatically collected by key, and the key is defined as the first half of the original array values.
Printing:
To print the result:
foreach($newArray as $key=>$newRow){
/// there are two rows in this case, [B.E] and [MSc]
print $key.":<br>";
print "<pre>";
///<pre> HTML tag makes output use linebreaks and spaces. neater.
print_r($newRow);
///alternatively use var_dump($newRow);
print "</pre>";
}
Alternatively if you wish to print a known named variable you can write:
print_r($newArray['B.E']);
Which will print all the data in that array. print_r is very useful.
what you want is php's explode. Not sure if this will give you the perfect answer but should give you an idea of what to do next.
$groupedArray = array();
foreach($array as $row){
$split = explode(" - ",$row);
$groupedArray[] = $split[0];
}
array_unique($groupedArray); //This will give you the two groupings
foreach($array as $row){
$split = explode(" - ",$row);
$pos = array_search($split[0],$groupedArray);
if($pos !== FALSE){
$groupedArray[$pos][] = $split[1];
}
}
This should give you a full formatted array called $groupedArray where $array is the array you already have.
Hope this helps!

Remove array elements based on value supplied

If I had an array like this...
array('1','2','3','4','10')
... how could I remove elements before the element whose value I supply.
For example:
If I supplied 1 then array = (1,2,3,4,10)
If it were 2 then array = (2,3,4,10) //Remove the numbers before 2
If it were 3 then array = (3,4,10) //Remove the numbers before 3
If it were 4 then array = (4,10) //Remove the numbers before 4
If it were 10 then array = (10) //Remove all before the 10
I'm currently thinking of doing with using if else. But is there a way to do this using some kind of php array function itself.
Make use of array_search and array_slice
<?php
$arr=array_slice($arr, array_search('4',array('1','2','3','4','10')));
print_r($arr);
OUTPUT :
Array
(
[0] => 4
[1] => 10
)
Demo
Maybe this would help:
$myArray = array('1','2','3','4','10');
$x=3;
$myArray = array_splice($myArray, array_search($x, $myArray), count($myArray));
$myArray = array('1','2','3','4','10');
$value = 3;
$key = array_search($value, $myArray);
$myNewArray = array_splice($myArray, 0, $key);
$array = array_filter($array, function($item) use ($filterItem) {
return $item !== $filterItem;
});
Will filter out every item equal to $filterItem. array_filter on php.net

How to append output of preg_match to an existing array?

I have two preg_match() calls and i want to merge the arrays instead of replacing the first array. my code so far:
$arr = Array();
$string1 = "Article: graphics card";
$string2 = "Price: 300 Euro";
$regex1 = "/Article[\:] (?P<article>.*)/";
$regex2 = "/Price[\:] (?P<price>[0-9]+) Euro/";
preg_match($regex1, $string1, $arr);
//output here:
$arr['article'] = "graphics card"
$arr['price'] = null
preg_match($regex2, $string2, $arr);
//output here:
$arr['article'] = null
$arr['price'] = "300"
How may I match so my output will be:
$arr['article'] = "graphics card"
$arr['price'] = "300"
?
You could use preg_replace_callback and handle the merging inside the callback function.
If it were me this is how I would do it, this would allow for easier extension at a later date, and would avoid using a callback function. It could also support searching one string easily by replacing $strs[$key] and the $strs array with a singular string var. It doesn't remove the numerical keys, but if you are only ever to go on accessing the associative keys from the array this will never cause a problem.
$strs = array();
$strs[] = "Article: graphics card";
$strs[] = "Price: 300 Euro";
$regs = array();
$regs[] = "/Article[\:] (?P<article>.*)/";
$regs[] = "/Price[\:] (?P<price>[0-9]+) Euro/";
$a = array();
foreach( $regs as $key => $reg ){
if ( preg_match($reg, $strs[$key], $b) ) {
$a += $b;
}
}
print_r($a);
/*
Array
(
[0] => Article: graphics card
[article] => graphics card
[1] => graphics card
[price] => 300
)
*/
You can use array_merge for this if you store your results in two different arrays.
But your output depicted above is not correct. You do not have $arr['price'] if you search with regex1 in your string but only $arr['article']. Same applies for the second preg_match.
That means if you store one result in $arr and one in $arr2 you can merge them into one array.
preg_match does not offer the functionality itself.
Use different array for second preg_match ,say $arr2
Traverse $arr2 as $key => $value .
Choose non null value out of $arr[$key] and $arr2[$key], and write that value to $arr[$key].
$arr will have required merged array.
This should work for your example:
array_merge( // selfexplanatory
array_filter( preg_match($regex1, $string1, $arr)?$arr:array() ), //removes null values
array_filter( preg_match($regex2, $string2, $arr)?$arr:array() )
);

Categories