For some reason I can't get strpos to work to search my array, even if $jobList[1] and $titlesearch are the same values... Sorry if it's something obvious but I'm still pretty new to coding!
I begin with my $data array which looks like this:
Array
(
[0] => P0001 Lifeguard descexample 18/09/18 parttime fixedterm mail vic
[2] => P0002 IT Manager descexample 18/09/18 fulltime ongoing post mail sa
)
I then explode each of these entries into their own array...
for ($i = 0; $i < count($data); $i++) {
$jobList = explode("\t", $data[$i]);
}
Array
(
[0] => P0001
[1] => Lifeguard
[2] => descexample
[3] => 18/09/18
[4] => parttime
[5] => fixedterm
[6] =>
[7] => mail
[8] => vic
)
Array
(
[0] => P0002
[1] => IT Manager
[2] => descexample
[3] => 18/09/18
[4] => fulltime
[5] => ongoing
[6] => post
[7] => mail
[8] => sa
)
Now I'm trying to search through these arrays from a user input, $titlesearch, and find it's matches with the job titles, $jobList[1]:
if (strpos($jobList[1], $titlesearch)) {
echo "nice one";
}
No matter what loops I try, the strpos never returns true, even if I echo the values and they both give the same result, so I'm really not sure what I'm doing wrong :'(
Any help is greatly appreciated!
You should always compare the data type when using this function as it may not return a boolean and it can be missleading. Check documentation here
Try it something like this:
if (strpos($jobList[1], $titlesearch) !== false) {
echo "nice one";
}
Related
This is the first post from a PHP noob. My question relates to an HTML/PHP form which posts the following three types of data generated by a MySQL query:
ID (always posted via a hidden input field)
Mileage (only some entries may be completed, others might be left blank)
Vehicle Type (always posted via a hidden input field)
This data is all for one of three companies that are selected on the page preceding the data-posting page ie.
Step One: Choose company and year. Press submit.
Step Two: See results from MySQL query and enter in mileages where necessary. Press submit.
Step Three: (that's why I'm here)
I've stuffed this data into what I (probably mistakenly) believe is a multidimensional array called $idmilearray by using the following code:
if(isset($_POST['mileage'])) {
$mileagenumber = $_POST['mileage'];
}
if(isset($_POST['idnos'])) {
$idnumber = $_POST['idnos'];
}
if(isset($_POST['vehicle'])) {
$vehicletype = $_POST['vehicle'];
}
$idmilearray = array(
'ids' => $idnumber,
'mileage' => $mileagenumber,
'vtype' => $vehicletype
);
foreach($idmilearray as $inputs) {
$inputs = $idmilearray['ids'];
$inputs = $idmilearray['mileage'];
$inputs = $idmilearray['vtype'];
}
If I execute a print_r on the $idmilearray I get the following results:
Array
(
[ids] => Array
(
[0] => 35
[1] => 22
[2] => 32
[3] => 38
[4] => 36
[5] => 39
[6] => 16
[7] => 20
[8] => 48
[9] => 46
)
[mileage] => Array
(
[0] => 334
[1] => 56
[2] =>
[3] => 43
[4] =>
[5] =>
[6] =>
[7] =>
[8] => 11
[9] => 5
)
[vtype] => Array
(
[0] => 10T
[1] => 10T
[2] => 10T
[3] => Artic
[4] => 10T
[5] => Artic
[6] => Artic
[7] => 10T
[8] => Artic
[9] => 10T
)
What I would like to do is to create another array (the values of which I can use in later SQL queries) but only where the keys contain something in [ids][0], [mileage][0] and [vtype][0] and so on and so forth. I'd like to use [mileage] as the 'reference array'.
I've been playing around with array_intersect_key and array_diff_key but I've hit a big and rather a nasty wall. Can anyone help or give some pointers?
Thanks very much for your time.
Regards,
External.
You can use what you have to insert directly into mysql as follows:
foreach ( $idmilearray['mileage'] as $KEY => $VAL ) {
if ( empty($VAL) ) continue;
$query = "INSERT INTO `tableName` (id, mileage, vtype) VALUES ('{$idmilearray['ids'][$KEY]}', '$VAL', '{$idmilearray['vtype'][$KEY]}')";
}
Or if you really want to merge everything for further processing or whatever reason you can do it like so:
$NewArray = [];
foreach ( $idmilearray['mileage'] as $KEY => $VAL ) {
if ( empty($VAL) ) continue;
$NewArray[] = array('id' => $idmilearray['ids'][$KEY], 'mileage' => $VAL, 'vtype' => $idmilearray['vtype'][$KEY]);
}
Ofcourse there are many other possible ways to do this, but these are the easiest given what you currently have.
Just add another foreach, inside your existing foreach and fill your new array by checking the old array values with if (!empty($old_array)) {}
Example:
foreach($idmilearray as $inputs) {
$inputs = $idmilearray['ids'];
$inputs = $idmilearray['mileage']; // This is the one you want, right?
$inputs = $idmilearray['vtype'];
}
To do the job you need, it would be something like this:
$new_array = []; // Short array syntax (PHP 5.3+)
foreach($idmilearray as $inputs) {
$inputs = $idmilearray['ids'];
foreach($idmilearray['mileage'] as $mileage) {
if (!empty($mileage)) {
$new_array[] = $mileage;
}
}
$inputs = $idmilearray['vtype'];
}
Now you have new array ($new_array) filled only with the keys that links to existing values.
I hope it helps you.
Currently I have an array like :
Array(
[0] => Array([range]=>1-10 [count]=>3 [type]=>A)
[1] => Array([range]=>11-20 [count]=>6 [type]=>A)
[2] => Array([range]=>21-30 [count]=>5 [type]=>A)
[3] => Array([range]=>1-10 [count]=>5 [type]=>B)
[4] => Array([range]=>11-20 [count]=>3 [type]=>B)
[5] => Array([range]=>21-30 [count]=>8 [type]=>B)
[6] => Array([range]=>1-10 [count]=>4 [type]=>C)
[7] => Array([range]=>11-20 [count]=>3 [type]=>C)
[8] => Array([range]=>21-30 [count]=>6 [type]=>C)
[9] => Array([range]=>1-10 [count]=>3 [type]=>D)
[10] => Array([range]=>11-20 [count]=>7 [type]=>D)
And then I am trying to regroup/remake the array depends on their type and the expected output would be like :
Array(
[0] => Array([type]=>A [1-10]=>3 [11-20]=>6 [21-30]=>5)
[1] => Array([type]=>B [1-10]=>5 [11-20]=>3 [21-30]=>8)
[2] => Array([type]=>C [1-10]=>4 [11-20]=>3 [21-30]=>6)
[3] => Array([type]=>D [1-10]=>3 [11-20]=>7)
)
I have tried array_column but isn't what exactly I want...
Example Here.
Thanks in advance.
This should work for you:
Here I simply loop through the entire array and then check with isset() if the result array already has an innerArray with the same type (e.g $result["A"]), if not I add the type as value to the inner array (.e.g. $result["A"]["type"] = "A";).
After this check I simply add the range and count to each type (e.g. $result["A"]["1-10"] = 3;)
At the end I simply reindex the entire $result array with array_values().
<?php
foreach($arr as $k => $v) {
if(!isset($result[$v["type"]]))
$result[$v["type"]]["type"] = $v["type"];
$result[$v["type"]][$v["range"]] = $v["count"];
}
$result = array_values($result);
print_r($result);
?>
output:
Array
(
[0] => Array
(
[type] => A
[1-10] => 3
[11-20] => 6
[21-30] => 5
)
//...
)
Im starting to get no ideias to solve this or probably its more simples than i expecpt.
Hope someone can help:
Im try to verify if
array A
arrA = Array
(
[0] => hindu
[1] => inglês
)
exists in array B
arrb = Array
(
[0] => active
[1] => awsome
[2] => speaker
[3] => creative
[4] => team leader
[5] => project manager
[6] => chinese
[7] => hindu
[8] => spanish
[9] => english
)
If(in_array($arrA , $arrB)){
echo true;
}
Meaning if the 2 elements of array A exist in Array B then return TRUE. ( Both elements not just one).
And the size of Array A is not always the same ( can have 1 to many elements).
I tryed in_array and various recursive functions, but no luck...
Anyone?
Thanks for the help in advance.
You can use array_diff() -
$all_elements_exist = count(array_diff($a, $b)) == 0 ? true : false;
Edit: Thanks to #Felix Kling and #mario for pointing me towards named capture groups and PREG_SET_ORDER, I totally learned something today.
I'm curious about a better algorithm per se, though. So please just pretend that there's no preg_match() involved.
Edit 2: Abstracted question
While answering another question here, I stumbled upon the fact that my code for turning
this:
Array
(
[0] => Array (
[0] => 1
[1] => 3
)
[1] => Array (
[0] => Description text
[1] => Different Description text
)
[2] => Array (
[0] => 123.456.12
[1] => 234.567.89
)
[3] => Array (
[0] => 10.00
[1] => 10.00
)
[4] => Array (
[0] => 10.00
[1] => 30.00
)
)
into that:
Array
(
[0] => Array
(
[qty] => 1
[description] => "Description text"
[sku] => 123.456.12
[price] => 10.00
[total] => 10.00
)
…
)
is fugly:
$field_names = array('qty', 'description', 'sku', 'price', 'total');
$result_arr = array();
$num_iter = count(matches[0]);
for ($i = 0; $i < $num_iter; $i++) {
foreach ($field_names as $index => $field_name) {
$result_arr[$i][$field_name] = array_shift($input_arr[$index]);
}
}
Any suggestions for improvement?
There is one simpler way to produce the desired output.
while (count($input_arr[0])) {
$values = array_map("array_shift", & $input_arr);
$result_arr[] = array_combine($field_names, $values);
}
This won't work past PHP 5.3, as it requires forcibly passing a parameter by reference. (Avoiding any dumbing-down-the-language remarks here). But you can of course chop off the entries with a more elaborate manual loop at any time.
The real simplification for such cases is however array_combine to turn a list into an associative array.
My code below produces an error, unknown modified "|"... I'm trying to use it as the OR operator. What is the correct way to run this code without error?
$p = "(\w+)|(\()|(\))|(\,)";
$s = "sum(blue,paper,green(yellow,4,toast)))";
preg_match($p,$s, $matches);
print_r($matches);
Edit
Okay I changed it a bit... ~(\w+|\(|\)|,)~
Now... here's the problem: I need to take that string and split it into an array like this:
array("sum","(","blue","paper","green","(" ... etc );
Can someone help me do that? when I run the above expression it outputs an empty array....
Thanks
You are missing the delimiter for your pattern.
$p = "~(\w+)|(\()|(\))|(\,)~";
You're missing the delimiter as #Crayon correctly mentioned, also this pattern does the same thing:
$p = '~(\w+|[(]|[)]|,)~';
As for your (new) problem, try this:
$p = '~([(),])~';
$str = 'sum(blue,paper,green(yellow,4,toast)))';
$res = preg_split($p, $str, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($res);
Output:
Array
(
[0] => sum
[1] => (
[2] => blue
[3] => ,
[4] => paper
[5] => ,
[6] => green
[7] => (
[8] => yellow
[9] => ,
[10] => 4
[11] => ,
[12] => toast
[13] => )
[14] => )
[15] => )
)